2013-07-14 134 views
0

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

} 
    } 
+1

對於Swing,通常使用基於AWT的較低級別KeyListener的鍵綁定。有關如何使用它們的詳細信息,請參見[如何使用鍵綁定](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html)。 –

+0

擴展Andrew的評論,你也可以查看[Motion Using the Keyboard](http://tips4java.wordpress.com/2013/06/09/motion-using-the-keyboard/)瞭解一些想法。 – camickr

回答

1

public void paintComponent(Graphics g)

frame.addKeyListener(this); 

刪除下面的行和下面的行添加到public static void main(String args[])

frame.addKeyListener(z); 

的問題是,後每repaint();通過keyPressed方法,所述paintComponent方法增加了一個新KeyListener到你的框架。
但是,如果您有幾個KeyListeners,則每個偵聽器將調用相同事件的keyPressed方法。因此,如果您有5個聽衆,並且您按一次右箭頭,則會調用keyPressed方法五次,並將x遞增五。
這意味着矩形會隨着右箭頭的每次擊中而快速移動。

+0

謝謝你親切的先生! :) –

-1

嘗試keyReleased,而不是keyPressed。它可能是這樣的,當鍵被按下時,它一直調用keyPressed事件。

+0

這不是要走的路!如果按住鍵,某些系統(基於AFAIR L * nux)將多次觸發按鍵/按鍵釋放事件。 –