出於某種原因,我的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();
}
}
}
請問您的面板具有焦點?您是否嘗試將KeyListener添加到根窗口? –