循环绘制矩形



我正在尝试制作一个基本的俄罗斯方块游戏,首先我希望绘制网格以确保我想创建块,但是我无法获得我的程序访问我的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);
         }
     }
 } 
}

这是一个可以完成您想要的基本代码:

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());

,重要的是,您需要一个 lep 重新绘制:

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

相关内容

  • 没有找到相关文章

最新更新