我想在按下箭头键时将图像在屏幕上向右移动16。我想以一个速度(1px/10ms)移动它直到达到该点。该图像是在JPanel的子类中创建的。 我写了下面的代码,但图像instatly改变位置而不是使运动:用Swing移动图像
public class Test extends JFrame implements KeyListener {
private int x=0;
private int y=0;
BufferedImage img;
...
...
public void paint(Graphics g){
g.drawImage(img,x,y,null);
}
// Move to a point 16 pixels to right
public void moveRight(){
for(int i=0;i<16;i++){
x++;
repaint();
try {
Thread.sleep(10); // Sleep 10 milliseconds until next position change
}catch (InterruptedException e) {}
}
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_RIGHT){
moveRight();
}
}
}
+1一个'javax.swing.Timer',显示在[here](http:// stackoverf low.com/q/9849950/230513)是此上下文中“SwingWorker”的替代方案。 – trashgod 2012-04-20 23:44:38