Could someone help me understand how the ACCELERATOR_KEY works in Java?

169 views Asked by At

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

There are 1 answers

1
camickr On

If I had to guess it seems the ACCELERATOR_KEY allows the user to assign a keyboard command to something

Correct.

However, if you read the ActionAPI you will see that the ACCELERATOR_KEY is only used for components that extend JMenuItem (except for JMenu).

If you want to use "A" as a KeyStroke to invoke an Action for the JCheckBox, then you need to use Key Bindings to manually do the binding by using the InputMap and ActionMap of 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 Menus and the demo code in that section demonstrates how to use an accelerator.

You can also try the How to Use Actions section. 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.