而不是使用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)。它应该帮助你。 –