我的 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");
}
}
}
}