简体   繁体   English

JPanel中的Java swing快捷键/键绑定

[英]java swing shortcut key / key bindings in a JPanel

I have a JPanel with lots of components in it. 我有一个JPanel,里面有很多组件。 When the user presses "a", I want to do something and consume the "a", EXCEPT if the user is in a textbox (or other part of the screen that accepts "a")--in that case, I don't want to know about the "a". 当用户按下“a”时,我想做某事并使用“a”,除非用户在文本框中(或接受“a”的屏幕的其他部分) - 在这种情况下,我不喜欢我想知道“一个”。

In the code below, I get notified of the "a", even if the focus is on a text box (typing "a" while in the textbox puts the "a" in the textbox and also notifies me about the "a"). 在下面的代码中,我收到“a”的通知,即使焦点在文本框上(在文本框中键入“a”,将“a”放在文本框中,并通知我“a”) 。

        JComponent jc = the panel...;
        InputMap inputMap = jc.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        ActionMap actionMap = jc.getActionMap();
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "qcAccept");
        actionMap.put("qcAccept", new AbstractAction("qcAccept") {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("A pressed, " + e);
            }
        });
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "qcAccept");

You are listening for the keyPressed event. 您正在侦听keyPressed事件。 Text components listen for the keyTyped event. 文本组件侦听keyTyped事件。 So that is why both bindings are still working. 这就是为什么两个绑定仍然有效。 Try: 尝试:

inputMap.put(KeyStroke.getKeyStroke("typed a"), "qcAccept");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM