KeyListener not working

一笑奈何 提交于 2019-11-26 22:26:39

问题


For some reason, my KeyListener just isn't responding to KeyPressed events.

If it matters, I'm on Ubuntu 12.04. It should be printing "Key Pressed" whenever a key is pressed, but it doesn't.

Here's the code:

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();
        }
    }
}

回答1:


  • Call super.paintComponent (not related to you question, but will solve some issues later on)
  • Make the component "focusable" - Component#setFocusable
  • Use key bindings over KeyListener
  • Use Component#requestFocusInWindow over Component#requestFocus...

From the Java Docs

Because the focus behavior of this method is platform-dependent, developers are strongly encouraged to use requestFocusInWindow when possible



来源:https://stackoverflow.com/questions/13354230/keylistener-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!