This week's book giveaway is in the HTML/CSS/JavaScript forum.
We're giving away four copies of Practical SVG and have Chris Coyier on-line!
See this thread for details.
Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

JTextField with ActionListeners?

 
Will Dietrich
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a long group of if statements under an action listener that perform some functions I need for a calculator project in my computer science class. I'm trying to add the functionality of allowing the user to press the enter key while the JTextField is selected and have the program perform a series of calculations. I could copy the code, which currently resides under an if statement in my action listener, over to a key released/key pressed method; however, I would rather keep everything under my ActionListener if it is possible. There is no real reason for this other than just wanting to keep things tidy. I am envisioning adding an || to the if statement in my action listener which I would like VK_ENTER to execute; however, I don't know how to get the command to a state where it can be compared using == or the like. We haven't really talked about using keyboard commands in class; however, this one line in the API for JTextField:
"How the text field consumes VK_ENTER events depends on whether the text field has any action listeners. If so, then VK_ENTER results in the listeners getting an ActionEvent, and the VK_ENTER event is consumed."
leads me to believe that it is possible to interpret a keyboard command with an action listener. I have been reading in the API about KeyEvents and KeyListeners; however, I am confused about control handling which is another reason I would like to keep everything under my ActionListener if it is possible. I guess the long and short of my question is: what would I need to do to have an ActionListener recognize and accept key presses from a JTextField?
 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You really don't have to do anything special to figure out if it was an Enter key. The actionPerformed is invoked only on the Enter key.
Just use myTextField.addActionListener()
 
Will Dietrich
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maneesh Godbole wrote:You really don't have to do anything special to figure out if it was an Enter key. The actionPerformed is invoked only on the Enter key.
Just use myTextField.addActionListener()


Ahhh, gotcha. I think that's what was confusing me, I was afraid that any key could trigger the action which is why I asked my question. Code is working now, thanks.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!