Sammy Guergachi
Sammy Guergachi

Reputation: 2006

Adding Keyboard support to Java Swing application regardless of Focus

I have a JFrame with multiple panels that accumulates in a fairly complex Swing UI. I want to add Keyboard support so that regardless of component focus a certain Key press, for example the [ENTER] key, causes a listener to react.

I tried adding a KeyListener to the JFrame but that doesn't work if another JComponent is selected which changes focus.

Is there a proper way to do this?

Upvotes: 0

Views: 778

Answers (2)

Kristian Kraljic
Kristian Kraljic

Reputation: 834

Registering a KeyEventDispatcher with the KeyboardFocusManager allows you to see all key events before they are sent to the focused component. You can even modify the event or prevent it from beeing delivered to the focused component:

KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(
    new KeyEventDispatcher() {
        public boolean dispatchKeyEvent(KeyEvent e) {
            //Get the char which was pressed from the KeyEvent:
            e.getKeyChar();
            //Return 'true' if you want to discard the event.
            return false;
        }
    });

If you just want to get the key inputs for one window / component or just for specific keys, you can use KeyBindings as kleopatra suggested. As an example on how to register to the keyboard event on Enter pressed (You may use any VK_ provided by KeyEvent, for modifiers [alt, ctrl, etc.] see InputEvent) see:

JFrame frame = new JFrame(); //e.g.
JPanel content = (JPanel)frame.getContentPane(); 
content.getInputMap().put(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ENTER,0),"enterDown");
content.getActionMap().put("enterDown",new AbstractAction() {
    private static final long serialVersionUID = 1l;
    @Override public void actionPerformed(ActionEvent e) {
        //This action is called, as the Enter-key was pressed.
    }
});

Upvotes: 1

thedayofcondor
thedayofcondor

Reputation: 3876

The way I do it is to make the JFrame focusable and append the listener to it. Then, iterate through all the JFrame children and make everything else not focusable. Of course this only works if you don't have text boxes or similar as they will become non editable.

Upvotes: 0

Related Questions