【发布时间】:2013-11-20 11:37:56
【问题描述】:
我有以下代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Exercise2 extends JFrame implements ActionListener{
public int x = 20 ,direction = 1;
public Exercise2(){
setSize(400, 200);
setTitle("Moving Car");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JButton move = new JButton("Move the car");
move.addActionListener(this);
add(move , BorderLayout.SOUTH);
setVisible(true);
}
public void paint(Graphics g){
super.paint(g);
g.drawRect(x, 80, 80, 50);
g.drawOval(x, 130, 30, 30);
g.drawOval(x+50, 130, 30, 30);
}
public void actionPerformed(ActionEvent e){
MyThread ex = new MyThread();
ex.start();
}
private class MyThread extends Thread {
public void run(){
while(true){
if(x >= getWidth()-70)
direction = -1;
else if (x <= 0)
direction = 1 ;
x += direction *10;
try{
Thread.sleep(100);
}catch(InterruptedException e){
System.exit(0);
}
repaint();
}
}
}
public static void main(String []args){
new Exercise2();
}
}
当我按下按钮时汽车开始移动但是如果我不将鼠标移到按钮上它会一直闪烁
我的问题:为什么会发生这种情况? ** & ** 如何解决?
新: 我将睡眠时间更改为 500 并且效果很好,但是如何在不更改睡眠时间的情况下解决它?
【问题讨论】:
-
我认为汽车图形可以更新。 :P
-
我把睡眠时间改成了500,效果很好,但是不改变睡眠时间怎么解决呢?
-
找到了解决办法。
标签: java multithreading jframe