简体   繁体   English

KeyListener不起作用

[英]KeyListener not working

For some reason, my KeyListener just isn't responding to KeyPressed events. 由于某种原因,我的KeyListener只是不响应KeyPressed事件。

If it matters, I'm on Ubuntu 12.04. 如果有关系,我使用的是Ubuntu 12.04。 It should be printing "Key Pressed" whenever a key is pressed, but it doesn't. 每当按下一个键时,它应该打印“ Key Pressed”,但不是这样。

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();
        }
    }
}
  • Call super.paintComponent (not related to you question, but will solve some issues later on) 调用super.paintComponent (与您的问题无关,但稍后会解决一些问题)
  • Make the component "focusable" - Component#setFocusable 使组件“可聚焦” Component#setFocusable
  • Use key bindings over KeyListener KeyListener使用键绑定
  • Use Component#requestFocusInWindow over Component#requestFocus ... Component#requestFocusInWindow上使用Component#requestFocus ...

From the Java Docs 从Java文档

Because the focus behavior of this method is platform-dependent, developers are strongly encouraged to use requestFocusInWindow when possible 由于此方法的焦点行为与平台有关,因此强烈建议开发人员在可能的情况下使用requestFocusInWindow

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM