gpt4 book ai didi

java - 按键监听器不工作

转载 作者:行者123 更新时间:2023-12-03 02:44:00 24 4
gpt4 key购买 nike

由于某种原因,我的 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
  • 使用key bindings通过KeyListener
  • 使用 Component#requestFocusInWindow 而不是 Component#requestFocus...

来自 Java 文档

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

关于java - 按键监听器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13354230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com