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()));
- Catch the event by a listener:
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.
You cannot use
JMenuItem
to create "hidden" short cuts. The short cuts ofJMenuItem
s become active once theJMenuItem
gets indirectly added to aWindow
(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.