[英]KeyListener not working
由於某種原因,我的KeyListener只是不響應KeyPressed事件。
如果有關系,我使用的是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();
}
}
}
super.paintComponent
(與您的問題無關,但稍后會解決一些問題) Component#setFocusable
KeyListener
使用鍵綁定 Component#requestFocusInWindow
上使用Component#requestFocus
... 從Java文檔
由於此方法的焦點行為與平台有關,因此強烈建議開發人員在可能的情況下使用requestFocusInWindow
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.