2

I have a frame which is multi tabbed and I have to set shortcuts to certain buttons under different tabs, but they have to use the same key. For example:

Under tab1, I have a "Do that" button which should react to F1 key, but if I were to switch to tab2, I should have a "Do this" button which should also react to F1 button but the action on tab1 shouldn't be fired.

I have tried adding keylistener to tabs/keys/panels but still, if I were to press F1 key, it's the first action that is fired.

But I think the reason is that I use a switch, which controls the key events, such as case KeyEvent.VK_F1:mybutton1.doclick();

So how do I separate actions to react separately under different tabs? Is there a way to get the focused tab for example or something else?

Regards.

Edit:some code for Swing action:

    private class SwingAction extends AbstractAction {
    public SwingAction() {
        putValue(NAME, "mybutton");
        putValue(SHORT_DESCRIPTION, "Some short description");
    }
    public void actionPerformed(ActionEvent e) {
        mybutton.getInputMap().put(KeyStroke.getKeyStroke("F1"),"pressed");
        mybutton.getActionMap().put("pressed",mybutton.doClick());

    }
}

i get :

The method put(Object, Action) in the type ActionMap is not applicable for the arguments (String, void) error, ( sorry a Java/Swing newbie here)

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Sin5k4
  • 1,556
  • 7
  • 33
  • 57

2 Answers2

4

use

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • cheers tried ' mybutton.getInputMap().put(KeyStroke.getKeyStroke("F1"),"pressed"); mybutton.getActionMap().put("pressed",mybutton.doClick());' couldnt get it to work.. :/ – Sin5k4 May 23 '12 at 08:14
  • no idea without posting an [SSCCE](http://sscce.org/), works for me, [rest is described here](http://stackoverflow.com/a/10674489/714968), your [SSCCE could be based on](http://stackoverflow.com/a/10591773/714968) , @Hovercraft Full Of Eels, Pete thank you for two great posts here :-) – mKorbel May 23 '12 at 08:16
  • excelent described issue about [JButton and KeyBindings](http://stackoverflow.com/a/10712202/714968) by @trashgod – mKorbel May 23 '12 at 08:35
3

Binding a KeyStroke to a button's doClick() has the advantage of visual and auditory feedback; but, as you've observed, doClick() is not an Action. Instead, create an Action that invokes a given button's doClick() method, and bind it to the desired KeyStroke, as shown in this example.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045