我的JPanel的KeyBindings工作正常,直到我从JFrame中删除JPanel,创建一个新的JPanel对象,然后将其添加到JFrame。
KeyBinding方法再次在新的JPanel对象上运行,但Keys不做任何事情。
以下是我用来展示问题的两个课程:
public class KeyBindingsTester {
static JFrame jf;
static KeyBindingPanel kp;
public static void main(String[] args){
new KeyBindingsTester();
}
public KeyBindingsTester(){
jf = new JFrame();
kp = new KeyBindingPanel();
jf.add(kp, BorderLayout.CENTER);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
public static void reset(){
jf.remove(kp);
kp = new KeyBindingPanel();
jf.add(kp,BorderLayout.CENTER);
jf.setVisible(true);
}
}
---------和小组:
public class KeyBindingPanel extends JPanel{
public KeyBindingPanel(){
setUpKeyBindings();
System.out.println("Keybindings set up");
}
public void setUpKeyBindings(){
addKeyBinding("B");
addKeyBinding("R");
}
public void addKeyBinding(String key){
getInputMap().put(KeyStroke.getKeyStroke(key), key);
getActionMap().put(key, new KeyBindingAction(key));
}
public class KeyBindingAction extends AbstractAction{
String action;
public KeyBindingAction(String actionName){
action = actionName;
}
public void actionPerformed(ActionEvent e){
if(action.equals("R")){
KeyBindingsTester.reset();
}
if(action.equals("B")){
System.out.println("BBB");
}
}
}
}
答案 0 :(得分:0)
问题在于焦点不在于JPanel。
更改此内容:getInputMap()。put(KeyStroke.getKeyStroke(key),key);
对此:getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(key),key);