hacky 的解决方案是调用requestFocusInWindow()
以JPanel
确保它具有焦点KeyListener
/KeyAdapter
这应该只在添加 Componnet 之后调用(尽管为了确保我的组件具有焦点,我在JFrame
通过revalidate()
and刷新之后调用它repaint()
)例如:
public class MyUI {
//will switch to the gamepanel by removing all components from the frame and adding GamePanel
public void switchToGamePanel() {
frame.getContentPane().removeAll();
GamePanel gp = new GamePanel();//keylistener/keyadapter was added to Jpanel here
frame.add(gp);//add component. we could call requestFocusInWindow() after this but to be 98% sure it works lets call after refreshing JFrame
//refresh JFrame
frame.pack();
frame.revalidate();
frame.repaint();
gp.requestFocusInWindow();
}
}
class GamePanel extends JPanel {
public GamePanel() {
//initiate Jpanel and Keylistener/adapter
}
}
但是,您应该使用 Swing KeyBinding
s(+1 到 @Reimeus 评论)。
在这里阅读以熟悉它们:
现在您已经阅读了,让我们展示另一个示例来帮助澄清(尽管 Oracle 做得很好)
如果我们想为您添加KeyBinding
一个特定的JComponent
ie JButton
,Esc可以这样做:
void addKeyBinding(JComponent jc) {
jc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false), "esc pressed");
jc.getActionMap().put("esc pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
System.out.println("Esc pressed");
}
});
jc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true), "esc released");
jc.getActionMap().put("esc released", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
System.out.println("Esc released");
}
});
}
上述方法将被称为:
JButton b=..;//create an instance of component which is swing
addKeyBinding(b);//add keybinding to the component
请注意:
1)你不需要两者KeyBindings
,我只是展示了如何获得不同的关键状态并使用Keybindings
.
2)此方法将添加一个Keybinding
只要Esc按下并且组件位于具有焦点的窗口中就会激活的,您可以通过指定另一个来更改它,InputMap
即:
jc.getInputMap(JComponent.WHEN_FOCUSED).put(..);//will only activated when component has focus