3

I have a JPanel with lots of components in it. 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".

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").

        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);
            }
        });
4

1 回答 1

2
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "qcAccept");

您正在监听 keyPressed 事件。文本组件侦听 keyTyped 事件。这就是为什么两个绑定仍然有效的原因。尝试:

inputMap.put(KeyStroke.getKeyStroke("typed a"), "qcAccept");
于 2013-05-03T00:11:44.180 回答