简体   繁体   中英

java swing shortcut key / key bindings in a JPanel

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);
            }
        });
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "qcAccept");

You are listening for the keyPressed event. Text components listen for the keyTyped event. So that is why both bindings are still working. Try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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