简体   繁体   中英

JFrame's keylistener with actionlistener

I'm trying to add a KeyListener to my JFrame and the key pressed will do all the code inside an ActionListener class.

Example :

When I press F1, it will trigger the ActionListener class. Doing all the instructions.

Any help? Thank you in advance.

Don't have a KeyListener "call" an ActionListener. Rather create a separate method with all the instructions and have both the KeyListener and the ActionListener call this same method.

Also in this situation, don't use a KeyListener which behaves capriciously when keyboard focus can change, and instead favor use of Key Bindings .

the key pressed will do all the code inside an ActionListener class.

Instead of using an ActionListener you can use an Action . An Action is basically the same as an ActionListner, but you can define extra properties which make it easier to use with the keyboard. Read the section from the Swing tutorial on How to Use Actions for more information and working examples. As a side note Swing components are designed to use Actions.

Once you create the Action you have different options:

  1. You can add the Action to a JMenuItem and if you defined the "accelerator" key then the Action will be invoked automatically when the F1 key is pressed.

  2. If you don't use a JMenuItem then you need to bind the KeyStroke to the Action manually. See the section from the Swing tutorial on [How to Make and Remove Key Bindings] for the basics of manually adding a binding.( http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html#howto ).

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