How to make all application components respond to a specific key event?

I mean, for example, pressing β€œF5” in a web browser will refresh the web page no matter where the focus is. How to do this in java with GUI? I can use addKeylistener for all components, but I am sure that it is not.

+4
source share
4 answers

You can use the Swing mechanism and the 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 } }); 
+6
source

The best solution for this kind of task is to register the listener in the standard KeyboardFocusManager , as I recently explained in this answer .

+3
source

Another option is to use the menu for your application. Then Refresh simply becomes a menu item in the menu, and you can assign F5 as an accelerator to a menu item. Behind the scenes, he will do key bindings for you.

This is a good approach because you now have your own graphical interface. The user can invoke the update by searching the menu for various parameters. Advanced users will eventually recognize the accelerator key and do not even use a mouse. Like the entire graphical interface, you should be able to call a function using the keyboard or mouse.

+2
source

You can add AWTEventListener in 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); 
0
source

Source: https://habr.com/ru/post/1337481/


All Articles