我使用setContentPane(new Gamepanel())从另一个类调用此类。 为什么线程t1没有调用run方法?Jpanel调用线程
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");
}
}
编辑
好吧,其实初始化线程的伎俩。像那
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");
}
}
}
我假设这是一个正确的方式开始在启动方法中放置一个游戏循环。 我打算去JFrame + JPanel +线程游戏循环(输入+更新+绘制)。我错了吗?
这应该抛出一个NullPointerException,因为你永远不会初始化't1'...你需要一个't1 = new Thread(this);'wherewhere。请注意,无论您试图达到什么目标,几乎肯定会有更好的方法。 – assylias
螺纹和摆动部件不能混用。阅读http://docs.oracle.com/javase/tutorial/uiswing/concurrency/ – Qwerky