Reputation: 1626
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)
Upvotes: 2
Views: 524
Reputation: 205785
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.
Upvotes: 3
Reputation: 109813
use
Swing Action for JButton, you can to set the same JBUtton#setAction() for any JCOmponents that implements Swing Action
KeyBindings (for F1
) with output to the Swing Action
, inside Action
you have to call JButton#doClick()
don't use KeyListener for Swing JComponents, ever
Upvotes: 4