3

出于某种原因,我的 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();
        }
    }
}
4

1 回答 1

8
  • 致电super.paintComponent(与您的问题无关,但稍后会解决一些问题)
  • 使组件“可聚焦” -Component#setFocusable
  • 使用键绑定KeyListener
  • 使用Component#requestFocusInWindowComponent#requestFocus...

来自 Java 文档

由于此方法的焦点行为与平台相关,因此强烈建议开发人员尽可能使用 requestFocusInWindow

于 2012-11-13T01:12:53.230 回答