Reputation: 701
I have tried multiple times to find out a solution on my own by consulting Google, but this question, as ridiculously easy as it seems, has no documented answer. It seems to me.
All I want to know is: How to call a method from a keystroke? Example: Pressing ctrl + up -> call method zoomUp();
ps: would be nice if that keystroke could be bound to a JTextPane.
Update
Until now my solution was to:
Create an Item: JMenuItem up = new JMenuItem("up");
Create a shortcut:
up.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_UP, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
up.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent event) { //Do stuff } });
(- never add the Item so it is a hidden shortcut) But this is obviously ridiculous.
Upvotes: 0
Views: 398
Reputation: 17945
You cannot use JMenuItem
to create "hidden" short cuts. The short cuts of JMenuItem
s become active once the JMenuItem
gets indirectly added to a Window
(usually via <-JMenu
<-JMenuBar
<-JFrame
). Without that link, it cannot be known whether or not the accelerator is to be triggered or not, as the same accelerator might trigger different actions in different application windows.
You need to use a KeyListener
on the component or frame in which you want to react.
Upvotes: 1