Win a copy of Java Concurrency Live Lessons this week in the Threads forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Key Listener help  RSS feed

 
adeeb alexander
Ranch Hand
Posts: 268
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all.
I have a simple application with a button and 2 textfields. I have used the card layout. My requirement is that when ever i press the enter key, the button must be pressed. I have tried the following and it worked. The problem is that if i have do much work, then that should be repeated in the key events, and also the buttons actionPerformed method. I need something like the button pressed so that only the required code would be written only once. See the code below which i tried, any other way please suggest.


Thanks and Regards
adeeb
 
Rob Spoor
Sheriff
Posts: 20904
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Skip the key listener, and use a shared ActionListener for both the text field and the button. When you add an ActionListener to a JTextField it's actionPerformed code gets called if you press enter, and that's just what you do.

Note that if you use an Action for the JButton you can use that as an ActionListener as well since Action extends ActionListener.

And just for your information, AbstractButton gives you the doClick methods
 
adeeb alexander
Ranch Hand
Posts: 268
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your reply Prime.
I have used a common method for both. Is this good or what you have said is doing good, if so Why?

Thanks
alexander
 
Rob Spoor
Sheriff
Posts: 20904
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using a common method is also a good solution. That's what I would have done if I weren't aware of either a JTextField's ActionListener behaviour or JButton's doClick methods.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!