views:

173

answers:

1

Hey,

When I set setAccelerator() to Control + A or Control + P and I run the program it doesn't detect the keystroke.

Here's the code:

  menuItem = new JMenuItem("About");
  menuItem.setActionCommand("About");
  menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, Event.CTRL_MASK));
  menuItem.setMnemonic(KeyEvent.VK_A);
  menuItem.addActionListener(this);
  menu.add(menuItem);

Then when it's pressed it should invoke the Action Listener:

public void actionPerformed(ActionEvent e) {

  if(e.getActionCommand().equals("About")) {

   System.out.println("About");

  }
}

I'm running it in Eclipse on a Mac if that matters.

+1  A: 

Control-A and Control-P are both keystrokes that may already be intercepted, depending on your platform and depending on what has keyboard focus. Control-A may already be intercepted and interpreted as "select all", and Control-P may already be intercepted and interpreted as "paste".

What if you select a less commonly-used keystroke instead of "Control-A", such as "Control-Shift-A" or "Control-B"? Here's a modified version of your code that uses Control-Shift-A instead of Control-A:

menuItem = new JMenuItem("About");
menuItem.setActionCommand("About");
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, Event.CTRL_MASK | Event.SHIFT_MASK));
menuItem.setMnemonic(KeyEvent.VK_A);
menuItem.addActionListener(this);
menu.add(menuItem);

I tested this change on my own system using the JMenu demo from the Swing tutorial, and I found (exactly as you did) that registering Control-A as the accelerator had no effect. However, registering Control-Shift-A as the accelerator worked perfectly.

Joe Carnahan