import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Exercise2 extends JFrame implements ActionListener, Runnable{
public int x = 20;
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){
Thread t = new Thread(this);
t.run();
}
public void run(){
for(int i = 0; i < 400; i += 10){
x += 10;
repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String []args){
new Exercise2();
}}
这是我第一次在这个网站上提问,所以我为我的错误提前道歉。
我目前正在研究线程,我应该通过按下按钮让汽车移动,但是当我按下按钮而不是移动时,它只会跳过并在我选择的时间后出现在另一侧。 我该如何解决这个问题?
最佳答案
t.run();
以上说法不正确。使用线程时,您需要使用:
t.start();
当您直接调用 run() 方法时,该方法在事件调度线程 (EDT) 上执行,该线程是重绘 GUI 的线程。当您告诉线程 hibernate 时,它无法重新绘制 GUI,直到循环执行完毕。请参阅 Swing 教程中关于 Concurrency 的部分了解更多信息。
此外,这不是进行自定义绘画的方式。自定义绘制是通过重写 JPanel 的 paintComponent(...)
方法来完成的。然后将面板添加到框架中。再次阅读 Custom Painting 上的教程.
关于java - 使用线程在 GUI 中对形状进行动画处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27461325/