I am trying to understand how the ACCELERATOR_KEY is used and what it does. I found a code example online that shows how it is used, but when I run the code nothing seems to happen.
If I had to guess it seems the ACCELERATOR_KEY allows the user to assign a keyboard command to something, but in this example when I press ‘A’, nothing happens. Any ideas or explainations would be most appreciated! Thank you!
// w w w . java 2 s .c o m
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.KeyStroke;
public class Main {
public static void main(String[] a) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Action action = new ShowAction();
JCheckBox button = new JCheckBox(action);
frame.add(button, BorderLayout.CENTER);
frame.setSize(350, 150);
frame.setVisible(true);
}
}
class ShowAction extends AbstractAction {
public ShowAction() {
super("About");
putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("A"));
putValue(Action.NAME, "Go to number ");
}
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("About Swing");
}
}
Correct.
However, if you read the
ActionAPI you will see that theACCELERATOR_KEYis only used for components that extendJMenuItem(except for JMenu).If you want to use "A" as a
KeyStroketo invoke anActionfor theJCheckBox, then you need to useKey Bindingsto manually do the binding by using theInputMapandActionMapof the check box.Read the section from the Swing turtorial on How to Use Key Bindings for more information.
Note the tutorial also has a section on
How to Use Menusand the demo code in that section demonstrates how to use an accelerator.You can also try the
How to Use Actionssection. The Actions used in that demo are used by both a menu item and a button. You can try adding an accelerator the the Action to see the difference between the two components.