c999999999
c999999999

Reputation: 41

How to make all components in an application respond to specific key event?

I mean, like, pressing 'F5' in web browser will refresh the web page regardless of where the focus is. How do i do this in Java with GUI app? I can do 'addKeylistener' to all components but I'm sure that's not the proper way.

Upvotes: 4

Views: 2913

Answers (4)

camickr
camickr

Reputation: 324207

Another option is to use a menubar for your application. Then Refresh just becomes a menu item on a menu and you can assign F5 as an accelerator to the menu item. Behind the scenes it will do the key bindings for you.

This is a good approach because now you have a self docummenting GUI. User can invoke refresh by searching the menu for various options. Advanced users will eventually learn the accelerator key and and not even use the mouse. Like all GUI design you should be able to invoke a function using either the keyboard or the mouse.

Upvotes: 2

user85421
user85421

Reputation: 29730

You may add an AWTEventListener to the java.awt.Toolkit

    AWTEventListener listener = new AWTEventListener() {            
        @Override
        public void eventDispatched(AWTEvent ev) {
            if (ev instanceof KeyEvent) {
                KeyEvent key = (KeyEvent) ev;
                if (key.getID() == KeyEvent.KEY_PRESSED && KeyEvent.getKeyText(key.getKeyCode()).equals("F5")) {
                    System.out.println(ev);
                    // TODO something meaningfull
                    key.consume();
                }
            }
        }
    };

    Toolkit.getDefaultToolkit().addAWTEventListener(listener, AWTEvent.KEY_EVENT_MASK);

Upvotes: 1

Riduidel
Riduidel

Reputation: 22308

The best solution for that kind of task is to register a listener into standard KeyboardFocusManager, like I recently explained in this answer.

Upvotes: 3

Russ Hayward
Russ Hayward

Reputation: 5667

You can use Swing's input and action map mechanism:

component.getRootPane().getInputMap(JRootPane.WHEN_IN_FOCUSED_WINDOW)
          .put(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0), "refresh");
component.getRootPane().getActionMap().put("refresh", new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // Code here
    }
});

Upvotes: 7

Related Questions