Hi,
I need to install an Action with a defined accelerator key without
using a corresponding JMenuItem. I've got a JButton to correspond with
the accelerator key, but no Menu item.
I've been looking at the code for JMenuItem and I found the code in
"installAction" in BasicMenuItemUI, but installing the keystroke this
way does not fire the action.
Anyone knows how to get this working?
Regards,
Bart
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class Test extends JFrame {
@Override
protected void frameInit() {
super.frameInit();
setLayout(new FlowLayout());
AAction acA = new AAction();
JButton btA = new JButton(acA);
installAction(btA, acA);
BAction acB = new BAction();
JButton btB = new JButton(acB);
installAction(btB, acB);
add(btA);
add(btB);
}
public static void main(String[] args) {
Test t = new Test();
t.setDefaultCloseOperation(EXIT_ON_CLOSE);
t.pack();
t.setLocationRelativeTo(null);
t.setVisible(true);
}
class AAction extends AbstractAction {
AAction() {
super("A");
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke("ctrl
A"));
}
public void actionPerformed(ActionEvent e) {
System.out.println("Test$AAction.actionPerformed");
}
}
class BAction extends AbstractAction {
BAction() {
super("B");
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke("ctrl
B"));
}
public void actionPerformed(ActionEvent e) {
System.out.println("Test$BAction.actionPerformed");
}
}
public static void installAction(JComponent c, Action a) {
KeyStroke accelerator = (KeyStroke)
a.getValue(Action.ACCELERATOR_KEY);
InputMap windowInputMap = SwingUtilities.getUIInputMap(c,
JComponent.WHEN_IN_FOCUSED_WINDOW);
if (windowInputMap != null) {
windowInputMap.clear();
}
if (accelerator != null) {
if (windowInputMap == null) {
windowInputMap = new ComponentInputMap(c);
SwingUtilities.replaceUIInputMap(c,
JComponent.WHEN_IN_FOCUSED_WINDOW,
windowInputMap);
}
windowInputMap.put(accelerator, "doClick");
}
}
}
Andrew Thompson - 04 Jan 2006 03:48 GMT
> I need to install an Action ..
Please refrain from multi-posting.

Signature
Andrew Thompson
physci, javasaver, 1point1c, lensescapes - athompson.info/andrew
Bart Cremers - 04 Jan 2006 11:59 GMT
I know, but I posted to the wrong group by accident and I don't know a
way to remove the wrong post
Andrew Thompson - 04 Jan 2006 12:21 GMT
> I know, but I posted to the wrong group by accident and I don't know a
> way to remove the wrong post
It is best *not* to remove posts, as there might be replies
on the way that will otherwise 'hang out in space'.
It is better, generally, to..
a) mention the wrong group/multi-post in the second post.
b) notify the first thread (add another message) that it is
being followed up on ...
HTH

Signature
Andrew Thompson
physci, javasaver, 1point1c, lensescapes - athompson.info/andrew