2016-12-04 114 views
0

我想製作一個基本的俄羅斯方塊遊戲,首先我要繪製一個網格以確保我創建了塊,但是我無法讓我的程序訪問我的paintComponent方法。循環繪製矩形

package tetris; 

import javax.swing.*; 
import java.awt.*; 

public class TetrisMain extends JFrame { 

final int BoardWidth = 10; 
final int BoardHeight = 20; 
public static int HEIGHT = 400; 
public static int WIDTH = 200; 

Timer timer; 
boolean isFallingFinished = false; 
boolean isStarted = false; 
boolean isPaused = false; 
int score = 0; 
int curX = 0; 
int curY = 0; 
int[][] grid = new int[BoardWidth][BoardHeight]; 

public static void main(String[] args) { 
    JFrame frame = new JFrame("Charles Walker - 1504185"); 
    frame.setSize(WIDTH, HEIGHT); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setLocationRelativeTo(null); 
    frame.setResizable(false); 
    frame.setVisible(true); 
    frame.repaint(); 
} 

public void paintComponent(Graphics g) { 
    super.paintComponents(g); 
    g.setColor(Color.BLACK); 
    for (int i = 0; i < BoardWidth; i++) { 
     for (int j = 0; j < BoardHeight; j++) { 
      curX = grid[i][curY]; 
      curY = grid[curX][j]; 
      g.fillRect(WIDTH/BoardWidth, HEIGHT/BoardHeight, curX, curY); 
     } 
    } 
} 
} 
+0

使用jpanel繪製graphics.and你爲什麼要創建另一個框架?'TetrisMain'是一個jframe –

+0

對不起,我只是在我發佈之前就把它拿出來了,但仍舊複製了舊代碼,忽略了這一點。至於使用JPanel進行繪製,這是如何工作的不同?以及如何訪問我的paintComponent來做到這一點? – Chaz

+0

jframe是一個沉重的組件,實際上它不是一個jcomponent,所以沒有paint組件的方法。它最好使用jpanel進行繪製。如果你從jpanel擴展clas,那麼你可以覆蓋paintComponent method.add'@ override'註釋你會看到問題 –

回答

0

這是一個基本的代碼做你想要什麼:

import javax.swing.JFrame; 
import java.awt.Graphics; 
import javax.swing.JPanel; 
import javax.swing.*; 

public class Name extends JFrame { 
    public Name() { 
     super("Name"); 
     setTitle("Application"); 
     setContentPane(new Pane()); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setSize(400,400); 
     setResizable(true); 
     setVisible(true); 
     while (true){ 
       try { //Update screen every 33 miliseconds = 25 FPS 
       Thread.sleep(33); 
       } catch(InterruptedException bug) { 
       Thread.currentThread().interrupt(); 
       System.out.println(bug); 
       } 
       repaint(); 
     } 
    } 
    class Pane extends JPanel { 
     public void paintComponent(Graphics g) { //Here is were you can draw your stuff 
      g.drawString("Hello World",0,20); //Display text 
     } 
    } 
    public static void main(String[] args){ 
     new Name(); 
    } 
} 

我想你忘記了該行設定的內容窗格:

setContentPane(new Pane()); 

和,重要的是,你需要a while循環重繪:

while (true){ 
    try { //Update screen every 33 miliseconds = 25 FPS 
    Thread.sleep(33); 
    } catch(InterruptedException bug) { 
    Thread.currentThread().interrupt(); 
    System.out.println(bug); 
    } 
    repaint(); 
}