我只是在做随机的东西与GUI,我来到这个问题。当我按右箭头键,矩形真的在X轴上移动,但距离移动不是恒定的。它提高很快,矩形并经过各按大moves.In我最近的代码行X=X+1
似乎工作得fine.Here是我的代码:矩形X轴移动问题
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class Buffer extends JPanel implements KeyListener{
public static JFrame frame;
public int x;
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(x,0,20,20);
frame.addKeyListener(this);
}
public static void main(String args[]){
Buffer z=new Buffer();
frame=new JFrame();
frame.setSize(500,500);
frame.setVisible(true);
frame.setFocusable(true);
frame.add(z);
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_RIGHT){
x=x+1;
repaint();
}
}
}
对于Swing,通常使用基于AWT的较低级别KeyListener的键绑定。有关如何使用它们的详细信息,请参见[如何使用键绑定](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html)。 –
扩展Andrew的评论,你也可以查看[Motion Using the Keyboard](http://tips4java.wordpress.com/2013/06/09/motion-using-the-keyboard/)了解一些想法。 – camickr