而不是使用while循環或不同的線程,您應該使用動畫java.swing.Timer
。這裏是基本的結構
Timer(int delay, ActionListener listener)
,其中延遲到重繪之間的延遲你想要的時間,listener
與回調函數來執行監聽。你可以做這樣的事情,在這裏你改變x
位置,然後調用repaint();
ActionListener listener = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (x >= D_W) {
x = 0;
drawPanel.repaint();
} else {
x += 10;
drawPanel.repaint();
}
}
};
Timer timer = new Timer(250, listener);
timer.start();
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyBindings extends JFrame {
private static final int D_W = 500;
private static final int D_H = 200;
int x = 0;
int y = 0;
DrawPanel drawPanel = new DrawPanel();
public KeyBindings() {
ActionListener listener = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (x >= D_W) {
x = 0;
drawPanel.repaint();
} else {
x += 10;
drawPanel.repaint();
}
}
};
Timer timer = new Timer(100, listener);
timer.start();
add(drawPanel);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
private class DrawPanel extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillRect(x, y, 50, 50);
}
public Dimension getPreferredSize() {
return new Dimension(D_W, D_H);
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new KeyBindings();
}
});
}
}
這裏是一個正在運行的例子
對我們發出更多的代碼 – Xabster
如何觸發'repaint()'? – Holger
看看[**如何使用鍵綁定**移動屏幕上的矩形](http://stackoverflow.com/a/20844242/2587435)。它應該幫助你。 –