键绑定不起作用,未执行操作

Key Binding not working, action not performed

我只是想了解密钥绑定器的工作原理,看来我误解了 Java 教程中的某些内容。这是代码:

public class KeyBinder {

    public static void main(String[] args) {

        //making frame and label to update when "g" key is pressed.

        JLabel keybinderTestLabel;

        JFrame mainFrame = new JFrame();
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setSize(300,75);
        mainFrame.setLocationRelativeTo(null);
        mainFrame.setVisible(true);

        keybinderTestLabel = new JLabel("Press the 'g' key to test the key binder.");
        mainFrame.add(keybinderTestLabel);

        Action gPressed = new AbstractAction(){

            @Override
            public void actionPerformed(ActionEvent e) {
                keybinderTestLabel.setText("Key Binding Successful.");
                System.out.println("Key Binding Successful.");
                //Testing to see if the key binding was successful.
            }

        };


        keybinderTestLabel.getInputMap().put(KeyStroke.getKeyStroke("g"), "gPressed");
        keybinderTestLabel.getActionMap().put("gPressed", gPressed);
        /*
         * from my understanding, these two lines map the KeyStroke event of the g key
         * to the action name "gpressed", then map the action name "gpressed" to the action
         * gpressed.
         * 
         */
    }

}

据我所知,我将 g 击键映射到操作名称 "gPressed",然后将其映射到操作 gPressed。但出于某种原因,当我 运行 程序时,按 g 键不会更新文本标签。这里有什么问题? "g" 击键实际上没有映射到键盘上的 g 键吗?

因此,来自 JavaDocs

public final InputMap getInputMap() Returns the InputMap that is used when the component has focus. This is convenience method for getInputMap(WHEN_FOCUSED).

由于 JLabel 不可聚焦,这将永远行不通,相反,您需要提供不同的聚焦条件,例如...

keybinderTestLabel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW). //...

此外,这是个人喜好...KeyStroke.getKeyStroke("g") 像这样使用 KeyStroke.getKeyStroke 可能会出现问题,因为您提供的 String 需要非常精确的含义,并且我永远不记得它应该如何工作(并且没有过多记录)。

如果第一个建议无法解决问题,请尝试使用 KeyStroke.getKeyStroke(KeyEvent.VK_G, 0) 代替