Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 668
c999999999 Avatar asked Dec 13 '22 16:12

c999999999


2 Answers

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
    }
});
like image 51
Russ Hayward Avatar answered Dec 15 '22 05:12

Russ Hayward


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

like image 25
Riduidel Avatar answered Dec 15 '22 05:12

Riduidel