English 中文(简体)
Java JMenu setAccelerator() problem
原标题:

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.

问题回答

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.

not sure if it will help, but you re using Event.CTRL_MASK instead of KeyEvent.CTRL_MASK





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签