Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

JtextField addKeyListener

 
Efrat Bar-Nahum
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have a text field and a button.
I want to disable the button when the text field is empty.
So I thought that the best thing to do was to check after every key pressed: when a character was entered I should enable the button, and when the text field is cleared I should disable it.
But when I use addKeyListener the text is not updated with the new changes yet. I can use the KeyEvent e.getKeyChar(); but it's starting to be a little complicated.(what if the user selected the whole text and deleted it?)

Is there a better way to get the correct text right after a key was pressed?

Thanks,
Efrat
 
Jared Cope
Ranch Hand
Posts: 243
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Originally posted by Efrat Bar-Nahum:
Hi,
I have a text field and a button.
I want to disable the button when the text field is empty.


What about if you add a focus listener to your text field and you take action when the focus leaves the textfield (ie, implement the focusLost method of the listener).

In the focusLost method you would get the text of your field, check if it equals "" and then take appropriate diabling/enabling actions on your button.

Cheers, Jared.
 
Efrat Bar-Nahum
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried, but the focus listener won't work if the user presses the button right after updating the text field. (In that case that focus is not lost until the button is pressed, and that's too late.)
 
Nick Meverden
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Efrat Bar-Nahum
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Exactly what I needed! (My problem was that I used keyTyped instead of KeyReleased)
Thanks a lot!
Efrat
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!