我用 setContentPane(new Gamepanel()) 从另一个类调用这个类。为什么线程 t1 没有调用 run 方法?
public class GamePanel extends JPanel implements Runnable {
public static int WIDTH = 1024;
public static int HEIGHT = WIDTH / 16 * 9;
private Thread t1;
boolean running;
public void addNotify(){
Dimension size = new Dimension(WIDTH,HEIGHT);
setPreferredSize(size);
running = true;
t1.start();
}
public void paintComponent (Graphics g){
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.BLACK);
g.fillOval(200, 200, 50, 50);
}
public void run() {
while (running){
System.out.println("Runs");
}
}
编辑
好吧,实际上初始化 Thread 就成功了。像那样
public class GamePanel extends JPanel implements Runnable {
public static int WIDTH = 1024;
public static int HEIGHT = WIDTH / 16 * 9;
private Thread t1;
boolean running;
public void addNotify(){
Dimension size = new Dimension(WIDTH,HEIGHT);
setPreferredSize(size);
running = true;
t1 = new Thread(this);
t1.start();
}
public void paintComponent (Graphics g){
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.BLACK);
g.fillOval(200, 200, 50, 50);
}
public void run() {
while (running){
System.out.println("Runs");
}
}
}
我假设这是开始在 start 方法中放置游戏循环的正确方法。我打算去 JFrame+JPanel+线程游戏循环(输入+更新+绘图)。我错了吗?