Tom*_*one 0 java swing multithreading
我做了一个简单的Java程序,它使用Thread对象在JPanel周围移动一个方块.方块移动到随机位置,更改其颜色,JPanel更改其背景颜色.然后线程休眠1000毫秒.但后来又添加了一行代码,为JLabel增加了+1,并且方块停止了移动(当分数正在工作并添加+1时).
这是代码:
@Override
public void run() {
Random random = new Random();
int width = 0;
int height = 0;
while(true) {
width = random.nextInt(area.getSize().width) + 1;
height = random.nextInt(area.getSize().height) + 1;
width -= ((width - 45) > 0) ? 45 : 0;
height -= ((height - 45) > 0) ? 45 : 0;
this.square.setLocation(width, height);
this.square.setIcon(new ImageIcon(getClass().getResource("/img/square" + (random.nextInt(4) + 1) + ".png")));
this.area.setBackground(new Color(random.nextInt(255) + 1, random.nextInt(255) + 1, random.nextInt(255) + 1));
//The following line works, but the setLocation method stops working.
this.score.setText(Integer.toString(Integer.parseInt(this.score.getText()) + 1));
try {
sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(RunThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
谢谢.
编辑:这就是我创建线程的方式......
public Click() {
initComponents();
pack();
setLocationRelativeTo(null);
setVisible(true);
RunThread run = new RunThread(jLabel1, jLabel2, jPanel1);
run.run();
}
Run Code Online (Sandbox Code Playgroud)
调用run()方法
哪个错了.那不是怎么用的Thread.如果你调用该run()方法,那么它只是像任何其他方法一样处理,你没有使用Thread.因此,无论何时使用,都会Thread.Sleep(...)导致Event Dispatch Thread(EDT)睡眠,这意味着GUI无法自行重绘.
用一个Thread.你需要在上面调用start()方法Thead,所以代码应该是:
run.start();
Run Code Online (Sandbox Code Playgroud)