简体   繁体   中英

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:

  • 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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM