2012-11-13 133 views
2

出於某種原因,我的KeyListener只是沒有響應KeyPressed事件。KeyListener不工作

如果重要,我在Ubuntu 12.04上。每按一次鍵就應該打印「Key Pressed」,但不是。

下面的代碼:

import java.awt.event.*; 
import javax.swing.*; 
import java.awt.Graphics; 

public class DisplayPanel extends JPanel 
{ 
    private Tile[][] tiles; 
    private Creature[] creatures; 
    private Dungeon dungeon; 
    private Player player; 

    public DisplayPanel(Dungeon dungeon, Tile[][] tiles, Creature[] creatures, Player player) 
    { 
     this.tiles = tiles; 
     this.creatures = creatures; 
     this.dungeon = dungeon; 
     this.player = player; 
     addKeyListener(new DungeonKeyListener()); 
     requestFocus(); 
    } 

    protected void paintComponent(Graphics g) 
    { 
     int maximum = (getWidth() < getHeight()) ? getWidth() : getHeight(); 
     for (Tile[] row : tiles) 
     { 
      for (Tile tile : row) 
      { 
       if (tile != null && tile instanceof Tile) 
       { 
        tile.draw(g, maximum/tiles.length, maximum/tiles[0].length); 
       } 
      } 
     } 
     for (Creature creature : creatures) 
     { 
      if (creature != null && creature instanceof Creature) 
      { 
       creature.draw(g, maximum/tiles.length, maximum/tiles[0].length); 
      } 
     } 

     if (player != null && player instanceof Player) 
     { 
      player.draw(g, maximum/tiles.length, maximum/tiles[0].length); 
     } 
    } 

    private class DungeonKeyListener extends KeyAdapter 
    { 
     public void keyReleased(KeyEvent e) 
     { 
      System.out.println("Key pressed!"); 
      dungeon.press(e.getKeyCode()); 
      repaint(); 
     } 
    } 
} 
+0

請問您的面板具有焦點?您是否嘗試將KeyListener添加到根窗口? –

回答

7
  • 呼叫super.paintComponent(不涉及您的問題,但可以解決以後對一些問題)
  • 使組件 「可聚焦」 - Component#setFocusable
  • 使用key bindings超過KeyListener
  • 使用Component#requestFocusInWindow超過Component#requestFocus ...

從Java文檔

因爲此方法的焦點行爲與平臺相關的, 開發者強烈建議使用requestFocusInWindow時 可能

+0

乾杯。關於第三點,我們必須使用KeyListeners進行作業:/ –

+0

另外,調用super.paintComponent有什麼意義? –

+0

'paintComponent'是繪畫鏈中的一個鏈接。超級版本確保UI保持一致狀態的重要工作。除非你願意接管它的責任,否則你應該調用'super.paintComponent' – MadProgrammer