问题描述
我发现,当我写pnlMap.add(map [i] [j])时,keylistener将无效。 map是JButton的集合,pnlMap是JPanel。
I found that, when I write "pnlMap.add(map[i][j])" keylistener won't work. map is set of JButton, pnlMap is JPanel.
公共游戏(玩家玩家)
{
public Game(Player player){
initComponents();
this.player = player;
loadPlayerInfo();
ImageIcon icon = new ImageIcon("images/items/sword_advanced.png");
this.setIconImage(icon.getImage());
addKeyListener(this);
map = new Square2[20][20];
for (int j = 0; j < 20; j++) {
for (int i = 0; i < 20; i++) {
map[i][j] = new Square2();
pnlMap.add(map[i][j]);
}
}
}
推荐答案
为了使 KeyListener
起作用,它注册的组件必须是可聚焦的并具有键盘焦点。大多数容器如 JComponent
和 JPanel
默认情况下不可聚焦(在考虑制作它们之前我会非常小心所以)。这意味着,当您添加可接受键盘焦点的组件(并且它接收键盘焦点)时,您的 KeyListener
将不再有效。
In order for KeyListener
to work, the component it is registered to MUST be focusable AND have keyboard focus. Most containers like JComponent
and JPanel
aren't focusable by default (and I'd be VERY careful before considering making them so). This means that the moment you add a component which can accept keyboard focus (and it receives keyboard focus), your KeyListener
will no longer work.
这是我们建议不要使用它的众多原因之一。相反,请使用Key Bindings API,它允许您确定组件为触发绑定所需的焦点水平
This is one of the many reasons we recommend against using it. Instead, make use of the Key Bindings API, which allows you to, among other things, determine the level of focus a component will need in order to trigger the bindings
参见了解更多详情
这篇关于当我向Jpanel添加按钮时,KeyListener不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!