我只是在做隨機的東西與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