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

时间:2017-11-29 20:10:36

标签: java swing key action

我只是想了解关键绑定器是如何工作的,而且我似乎误解了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键?

1 个答案:

答案 0 :(得分:3)

所以,来自JavaDocs

  

public final InputMap getInputMap()   返回使用的InputMap   当组件具有焦点时。这是方便的方法   getInputMap(WHEN_FOCUSED)

由于JLabel不可调焦,因此无法使用,相反,您需要提供不同的焦点条件,例如......

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

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

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

相关问题