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.
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
}
});
The best solution for that kind of task is to register a listener into standard KeyboardFocusManager
, like I recently explained in this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With