2015-06-21 105 views
0

所以這是我的代碼:爲什麼我的動畫不可見?

import javax.swing.*; 
import java.awt.event.*; 

public class Frame { 

Draw d = new Draw(); 

JFrame f1 = new JFrame("Animation 2"); 
JButton bMoveRight = new JButton(">>>>"); 
JButton bMoveLeft = new JButton("<<<<"); 

public Frame() { 

    f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    f1.setSize(800, 600); 
    f1.setVisible(true); 
    f1.setResizable(false); 
    f1.setLocationRelativeTo(null); 

    bMoveRight.setBounds(50, 450, 120, 50); 
    bMoveLeft.setBounds(600, 450, 120, 50); 

    f1.add(bMoveRight); 
    f1.add(bMoveLeft); 

    f1.add(d); 

    bMoveRight.addActionListener(new ButtonMoveRight()); 
    bMoveLeft.addActionListener(new ButtonMoveLeft()); 

    } 

    private class ButtonMoveRight implements ActionListener { 
     public void actionPerformed(ActionEvent e){ 
      d.animateRight(); 
     } 
    } 

    private class ButtonMoveLeft implements ActionListener { 
     public void actionPerformed(ActionEvent e){ 
      d.animateLeft(); 
     } 
    } 

} 

import javax.swing.*; 
import java.awt.*; 

public class Draw extends JComponent{ 

int x = 50; 

public void paint(Graphics g){ 
    g.setColor(Color.BLACK); 
    g.fillRect(x, 150, 200, 100); 
} 

public void animateLeft(){ 
    try{ 
     while(x != 50){ 
      x--; 
      repaint(); 
      Thread.sleep(10); 
     } 
    } catch(Exception ex){ 
     ex.printStackTrace(); 
    } 
} 

public void animateRight(){ 
    try{ 
     while(x != 550){ 
      x++; 
      repaint(); 
      Thread.sleep(10); 
     } 
    } catch(Exception ex){ 
     ex.printStackTrace(); 
    } 
} 
} 

一切正常,因爲它應該。除了一件事。我的動畫發生,但問題是它不顯示。我做了另一個程序中僅有的動畫並開始向右走,但在這其中我做了按鈕來啓動動畫。會發生什麼事是我按一下按鈕,沒有任何反應,持續5秒(這就是它需要去另一邊的時間),5秒後它出現在窗口的另一側。爲什麼我的動畫不會顯示?

+0

看看[併發在Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/)和[如何使用Swing定時器(http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html)瞭解更多詳情 – MadProgrammer

回答

2

Thread.sleep代碼()內的 「ActionListener的」 回調是強烈反對。問題是:你的代碼是在同一個線程這是GUI應用程序的主線程中調用 - 它是用來繪製你的界面。

你需要做的睡眠,而不是()調用 - 你可以觸發一些事件與延遲和處理正確的方式。你必須使用像定時器 - 可能是這一個https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html