2014-12-13 99 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