开发者

Setting a key-binding to perform the same action as in my action listener

I have a JButton that's attached to an ActionListener, but I also wanted to add a shortcut key to the button to be more user-friendly. Say, the user can click the button and the program performs some function "f" or the user can also press "Enter" on the keyboard to perform the same function f. So here's what the gist of my code looks like

private JButton button;

public static void main(String[] args){
    Action buttonListener = new AbstractAction() {
         public void actionPerformed(ActionEvent e) {
                //Perform function f    
         }
    };

button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("ENTER"),
                        "test");
button.getActionMap().put("test",
                         buttonListener);

button.addActionListener(new OtherListener());
}

private class OtherListener implements ActionListener{
    public void actionPerformed(ActionEvent e){
        //Perform function f
    }
}

Seems a bit tedious having to add an Action and an ActionListener to do the same thing. Maybe I'm not seeing it, but is there a way t开发者_如何学JAVAo cut the code down so I can eliminate the Action and just use the actionListener? I was thinking switching the buttonListener parameter in the getActionMap().put() method to but the method only takes Action types.


Action extends ActionListener, so you should be able to define a single Action and use it wherever you need an ActionListener.

e.g.

public static void main(String[] args){
    Action buttonListener = new Action() {
         public void actionPerformed(ActionEvent e) {
                //Perform function f    
         }
    };
    button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
        .put(KeyStroke.getKeyStroke("ENTER"), "test");
    button.getActionMap().put("test", buttonListener);
    button.addActionListener(buttonListener);
}


JRootPane has a method setDefaultButton(...) that will do what you want. You will need to get the root pane from the top-level container, then you can call this method passing a reference to your JButton, and it will perform its action when enter is pressed on the GUI. And this makes sense when you think about it as "enter" is a special key, one whose behavior should be the responsibility of the GUI, not a single button.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜