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秒後它出現在窗口的另一側。爲什麼我的動畫不會顯示?
看看[併發在Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/)和[如何使用Swing定時器(http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html)瞭解更多詳情 – MadProgrammer