如果我在不启动线程的情况下调用函数draw,它将起作用,但是如果我尝试建立游戏循环。因此,我认为错误在于我如何开始游戏循环,但我不知道如何纠正它。
import java.awt.Dimension;
import javax.swing.*;
public class GameWindow{
public static final int WIDTH = 640;
public static final int HEIGHT = 480;
public static void main(String[] args) {
JFrame frame = new JFrame();
GamePanel panel = new GamePanel();
frame.setSize(new Dimension(WIDTH, HEIGHT));
frame.setMaximumSize(new Dimension(WIDTH, HEIGHT));
frame.setMinimumSize(new Dimension(WIDTH, HEIGHT));
frame.setPreferredSize(new Dimension(WIDTH, HEIGHT));
frame.setLocationRelativeTo(null);
frame.setTitle("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setVisible(true);
}
}
我也尝试只在一个类中编写所有内容,但仍然无法正常工作:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
public class GamePanel extends JComponent implements Runnable{
private Graphics2D g2;
private boolean isRunning = false;
public void paintComponent(Graphics g) {
g2 = (Graphics2D) g;
if(isRunning)
return;
isRunning = true;
new Thread(this).start();
}
@Override
public void run() {
while(isRunning) {
update();
draw();
}
}
private void draw() {
Rectangle r = new Rectangle(10, 10, 10, 10);
g2.setColor(Color.BLACK);
g2.draw(r);
}
private void update() {
// TODO Auto-generated method stub
}
}