Question

I have a JMenuItem:

JMenuItem menuItemNext = new JMenuItem("Next");

How can I change this so it can be activated by the Page Up keyboard button?

Also if you could explain how I could make a keyboard shortcut for another JMenuItem that uses ctrl + [right arrow] that would be great!

Was it helpful?

Solution

Try with:

JMenuItem menuItemNext = new JMenuItem("Next");
menuItemNext.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0));

For the another item:

menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 
     ActionEvent.CTRL_MASK));

There is two right arrows:

  • KeyEvent.VK_KP_RIGHT, Constant for the numeric keypad right arrow key.
  • KeyEvent.VK_RIGHT, Constant for the non-numpad right arrow key.

See more in How to Use Key Bindings (The Java Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top