2014-09-29 41 views
2

所以我想將字符串移向用戶推送的方向,但它不起作用。它與mouselistener一起工作,所以我認爲這是足夠的。我應該把聽衆添加到其他東西嗎?在JFrame上使用KeyListener來移動組件

public class Snake extends JComponent implements KeyListener{ 

    private int x; 
    private int y; 
    private String s; 

    public Snake(String s, int x, int y){ 
     this.s = s; 
     this.x = x; 
     this.y = y; 
     addKeyListener(this); 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     g.drawString(s, x, y); 
    } 


    @Override 
    public void keyTyped(KeyEvent e) { 

    } 

    @Override 
    public void keyPressed(KeyEvent e) { 
     int code = e.getKeyCode(); 
     switch(code) { 
      case KeyEvent.VK_UP: 
       y-=15; 
      case KeyEvent.VK_DOWN: 
       y+=15; 
      case KeyEvent.VK_RIGHT: 
       x+=15; 
      case KeyEvent.VK_LEFT: 
       x-=15; 
     } 
     repaint(); 
    } 

    @Override 
    public void keyReleased(KeyEvent e) { 

    } 
} 

public class Game { 

    public static void main(String[] args){ 
     JFrame frame = new JFrame("Up Up And Away!"); 
     JComponent star = new Snake("*", 250, 100); 
     frame.add(star); 
     frame.setSize(500, 300); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setVisible(true); 
    } 
} 
+0

避免使用'KeyListener'爲了這個目的,可以使用[鍵綁定(http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html),而不是 – BackSlash 2014-09-29 06:51:29

+0

檢查這個環節可能是對你有幫助。 http://stackoverflow.com/questions/286727/java-keylistener-for-jframe-is-being-unresponsive – Rana 2014-09-29 06:59:44

+0

http://stackoverflow.com/a/26098190/1966247這裏我已經解決了你的問題,你檢查它:),我希望你會得到它有幫助 – Muhammad 2014-09-29 11:02:09

回答

1

正如別人提到的那樣。這可能更好使用Key Bindings。但在你的情況下,你的焦點在別的地方,所以你的組件只需要抓住焦點。只需添加star.grabFocus();主要是。即:

public static void main(String[] args){ 
    JFrame frame = new JFrame("Up Up And Away!"); 
    JComponent star = new Test2("*", 250, 100); 
    frame.add(star); 
    frame.setSize(500, 300); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setVisible(true); 

    star.grabFocus(); 
} 

然後它應該工作。

+0

http://stackoverflow.com/questions/17680817/difference-between-requestfocusinwindow-and-grabfocus-in-swing#comment25758510_17680818 - 相關 – Gorbles 2014-09-29 10:25:01

+0

好或許requestFocusInWindow(..)更好:) – 2014-09-29 10:42:07

+0

我認爲他應該使用他的Snake類中使用的keyListener,就像我在這裏http://stackoverflow.com/a/26098190/1966247,它工作 – Muhammad 2014-09-29 10:57:58

1

您的KeyListener應用於JComponent,但不在JFrame上,當您運行程序時JFrame具有焦點(只有JFrame可以收聽KeyEvents),將以下行添加到您的Game類,然後它應該工作:)

frame.addKeyListener((KeyListener)star);