开发者

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

开发者 https://www.devze.com 2023-02-07 11:51 出处:网络
I mean, like, pressing \'F5\' in web browser will refresh the web page regar开发者_如何学Pythondless of where the focus is. How do i do this in Java with GUI app? I can do \'addKeylistener\' to all co

I mean, like, pressing 'F5' in web browser will refresh the web page regar开发者_如何学Pythondless 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.


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.


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消