Reputation: 1
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.
Upvotes: 0
Views: 424
Reputation: 324118
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:
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.
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).
Upvotes: 1
Reputation: 285403
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.
Upvotes: 1