2014-12-13 77 views
0
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(); 
}} 

这是我第一次在这个网站上提问,所以我提前为我的错误道歉。用线程在GUI中动画形状

我目前正在学习线程和即时通讯应该让汽车按下按钮,但当我按下按钮,而不是移动它只是跳过,并在我选定的时间后出现在另一侧。 我该如何解决这个问题?

回答

2
t.run(); 

以上错误。当使用一个线程,你需要使用:

t.start(); 

当您直接调用run()方法,该方法执行的事件指派线程(EDT),这是重绘GUI线程。当你让线程进入睡眠状态时,它不能重新绘制GUI,直到循环结束执行。有关更多信息,请参阅Concurrency上的Swing教程部分。

此外,这不是在做自定义绘画的方式。自定义绘画是通过覆盖JPanel的paintComponent(...)方法完成的。然后将面板添加到框架。再次阅读关于Custom Painting的教程。

+0

非常感谢你,修复它。我仍然需要了解线程... – ProgrammerAtSea 2014-12-14 18:52:09