Install keystroke on action without using a JMenuItem

B

Bart Cremers

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");
}
}
}
 
A

Andrey Kuznetsov

JComponent.registerKeyboardAction();

sorry, this is old obsolete method.

use a combination of getActionMap() and getInputMap():
if you want to bind Action a to KeyStroke ks, then use following:

String command = "<whatever>";
int condition; //one of WHEN_IN_FOCUSED_WINDOW, WHEN_FOCUSED,
WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
component.getInputMap(condition).put(ks, command);
component.getActionMap().put(commmand, a);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,816
Latest member
SapanaCarpetStudio

Latest Threads

Top