为什么没有任何东西吸引到JFrame?

时间:2018-09-11 18:14:04

标签: java jframe jpanel repaint 2d-games

运行代码时,应该在屏幕顶部弹出一个矩形。这是我的代码。

package game;

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

public class Game extends JFrame{
    Shapes shapes = new Shapes();
    static Long lastshapemake;
    boolean running = true;
    int count = 0;
    String color;
    public static int RotationIndex = 0;

Game(){
    setSize(200, 400);
    setTitle("Tetris");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
}

public static void main(String[] args) {
    Runnable r = new IsKeyPressed();
    Thread t = new Thread(r);
    t.start();
    Game game = new Game();
    game.run(game);
}

public void run(Game game) {
    shapes.newshape();
    while(true) {
        lastshapemake = System.nanoTime();
        long lastTime = System.nanoTime();
        double Target_FPS = 60.0;
        double ns = 1000000000 / Target_FPS;
        double delta = 0;
        while(running) { 
            long now = System.nanoTime();
            delta += (now - lastTime) / ns;
            lastTime = now;
            while(delta >= 1) {
                tick();

                game.repaint();
                delta--;

            }

        }    
    }
}

public static void rotate() {
    System.out.println('h');
    RotationIndex++;
    RotationIndex %= 4;
}
void tick() {
    if(shapes.list.get(shapes.list.size() - 1).arr[RotationIndex][1] == 180){//if current shapes lowest rectangle(always the fourth) touches ground
        lastshapemake = System.nanoTime();
        shapes.newshape();
    }
}




@Override
public void paint(Graphics g) {
    super.paint(g);
    for(Rectangles emp: shapes.list) {
        g.setColor(emp.color);
        //Loop through all rectangle objects
            //Loop through each objects array
            for(int i = 0; i < 7; i += 2) {
                g.drawRect(emp.arr[RotationIndex][i], emp.arr[RotationIndex][i + 1], 20, 20);
                g.fillRect(emp.arr[RotationIndex][i], emp.arr[RotationIndex][i + 1], 20, 20);
        }}      
}

}

什么都没有画到屏幕上,我也不知道为什么。在绘制矩形之前,我在添加super.paint(g)之前就可以使用它,但是在绘制新矩形之前,我需要调用super.paint(g)来清除矩形。我不知道必须解决此问题,以便仍然清除矩形然后再绘制矩形。感谢您的帮助。

0 个答案:

没有答案