2016-12-04 66 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(); 
}