• Post Reply Bookmark Topic Watch Topic
  • New Topic

JTextField and KeyEvents ...  RSS feed

 
Tom Diamond
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I have a JTextField and I want to capture key events from it. OK, I've written a nice KeyAdapter class and added it to the text field. But it seems that the event is proccessed firstly in my class and then in the JTextField's keyEvent listener. What I am saying is that I want to use the getText() method in my custom keyTyped() but it returns the text in the field without the last char.
So is there a way to send the keyEvent to the text field before I proccess it so that the text that getText() returns will be updated?
Tnx,
Tom.
 
Joe Gilvary
Ranch Hand
Posts: 152
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That sounds weird.
If you do not find some more elegant way to
handle it, how about appending the
KeyEvent.getKeyChar() to the String that you
can see?
HTH,
Joe
 
Tom Diamond
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, that is what I thought at first but the problem is that I have to take care of non-printable chars (i.e. Backspace - Delete) and also see if the user has selected some text. I wonder if there is a better way to do it ...
Tom.
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Tom,
The cleanest approach would be to extend the JTextField and override the processKeyEvent method. This would make sure that the keyEvent was handled by the TextField before you do your thing. See the code below for an example.

Regards,
Manfred.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!