钥匙及;按钮兼容性Java
我已经用Java制作了我自己的俄罗斯方块版本,并且添加了使用JButton和某些键盘键移动形状的可能性。我使用的代码片段如下所示:钥匙及;按钮兼容性Java,java,swing,jbutton,key-bindings,Java,Swing,Jbutton,Key Bindings,我已经用Java制作了我自己的俄罗斯方块版本,并且添加了使用JButton和某些键盘键移动形状的可能性。我使用的代码片段如下所示: leftButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent E) { moveLeft(); } }); rightButton.addActionListe
leftButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent E) {
moveLeft();
}
});
rightButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent E) {
moveRight();
}
});
rotateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent E) {
rotateMovingShape();
}
});
myPanel.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent event) {
int keyCode = event.getKeyCode();
if (keyCode == event.VK_A)
{
moveLeft();
}
if (keyCode == event.VK_D)
{
moveRight();
}
if (keyCode == event.VK_S)
{
rotateMovingShape();
}
}
});
我的问题是,在我使用JButtons之后,我再也不能用键盘键控制形状了。我怀疑这与获得/失去注意力有关,但我不确定。有人能告诉我发生了什么吗?你会遇到这个问题,因为你使用的是
KeyListener
,而不是你需要使用的。例如:
component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_A,0), "aPressed");
component.getActionMap().put("aPressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("a key");
}
});
component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_D,0), "dPressed");
component.getActionMap().put("dPressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("d key");
}
});
// other bindings
其中,
component
是您的JPanel
按键侦听器仅在该组件具有键盘焦点时接收按键事件。点击按钮将焦点转移到它们身上,并从面板上移开,这样您就不会看到事件。以下任何一种方法都可以解决此问题:
- 调用
setFocusable(false)对按钮进行编码>以使其不会窃取焦点
- 将KeyListener也添加到按钮中
- 使用而不是KeyListener,这样无论组件是否具有焦点,都可以捕捉按键