Haeri
Haeri

Reputation: 701

java keystroke method call

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:

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

Answers (1)

Christian Hujer
Christian Hujer

Reputation: 17945

You cannot use JMenuItem to create "hidden" short cuts. The short cuts of JMenuItems 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

Related Questions