[英]KeyListener doesn't work when I add button to Jpanel
I found that, when I write "pnlMap.add(map[i][j])" keylistener won't work. 我发现,当我编写“ pnlMap.add(map [i] [j])”时,键侦听器将无法工作。 map is set of JButton, pnlMap is JPanel.
map是JButton的集合,pnlMap是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]);
}
}
}
In order for KeyListener
to work, the component it is registered to MUST be focusable AND have keyboard focus. 为了使
KeyListener
正常工作,必须将其注册为可聚焦的组件并使其具有键盘焦点。 Most containers like JComponent
and JPanel
aren't focusable by default (and I'd be VERY careful before considering making them so). 默认情况下,大多数容器(例如
JComponent
和JPanel
都不可聚焦(在考虑使它们成为容器之前,我会非常小心)。 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. 这意味着,当您添加一个可以接受键盘焦点的组件(并且它可以接收键盘焦点)时,
KeyListener
将不再起作用。
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
相反,请使用Key Bindings API,该API允许您确定组件触发触发绑定所需的焦点级别。
See How to Use Key Bindings for more details 有关更多详细信息,请参见如何使用键绑定 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.