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

Answers


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

Need Your Help

C and pointer in a function - changes do not save

c arrays string pointers char

I have this simple code that seems to work (I checked with the debugger) but when the function execution ends, the string is not saved in the original variable.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.