I dont have any clue about code , any help would be appreciated
I am uploading an image of requirements , you can see that for particular toolbar i want to implement all shortcut key available , but i dont have any clue , where to start
I dont have any clue about code , any help would be appreciated
I am uploading an image of requirements , you can see that for particular toolbar i want to implement all shortcut key available , but i dont have any clue , where to start
First thought: "that's easy, RTFT", spitting out the first code snippet:
Action action = new AbstractAction("clear text") {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("triggered the action");
}
};
action.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("F1"));
JToolBar bar = new JToolBar();
bar.add(action);
// set toolbar to frame and be happy
Guess what happens on pressing F1 ... right, nothing.
It turns out that buttons in a toolBar - unlike their menu counterpart - do not support accelerator keys by default. That's unexpected to me (anybody else?), and may have several reasons
the second might well be the case as typically, the toolBar buttons kind of "double" menu items: that being the case, the accelerator is set on the menu item (and if everything has been set up correctly and the same action used in both) it is triggered auto-magically.
Now the question is, whether or not the OP has a menu/bar in his/her application as well. Complete answer depends on that: if so, simply use the same action as above
menu.add(action);
If it's really a stand-alone toolBar, not backed by a menu, slightly more work is involved, basically as outlined in a previous answer which is to explicitly add the keyBinding to the button added to the toolBar, something like:
JToolBar bar = new JToolBar();
JButton toolBarButton = bar.add(action);
toolBarButton.getActionMap().put("myAction", action);
toolBarButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
(KeyStroke) action.getValue(Action.ACCELERATOR_KEY), "myAction");
If this is a standard requirement for a given context for many buttons, subclass JToolBar, override the add(Action) method and do it there after calling super:
public class JXToolBar extends JToolBar {
public JButton add(Action action) {
JButton button = super.add(action);
KeyStroke stroke = (KeyStroke) action.getValue(Action.ACCELERATOR_KEY);
if (stroke != null) {
// do the input/actionMap config here
}
}
}