Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / May 2004

Tip: Looking for answers? Try searching our database.

Monitoring typing in JTextField

Thread view: 
Adam - 26 May 2004 03:42 GMT
I want to run a piece of code everytime the text in a JTextField changes. I
have managed to detect a key press by adding a KeyListener, but if i call
textField.getText(), it returns the previous value. How do I get the new
text that will be there after this new keystroke is processed?
I can't be too complicated surely?!?!

adam
Woebegone - 26 May 2004 04:41 GMT
> I want to run a piece of code everytime the text in a JTextField changes. I
> have managed to detect a key press by adding a KeyListener, but if i call
[quoted text clipped - 3 lines]
>
> adam

Hi Adam,

You should look into adding a DocumentListener to your JTextComponent. And
unless you find some really compelling reason to worry about key actions
<shudder/>, don't.

hth,
Sean.
Woebegone - 28 May 2004 03:52 GMT
> Hi Adam,
>
> You should look into adding a DocumentListener to your JTextComponent. And

Sorry -- could have been a bit more helpful. Depending on what you want, you
can implement a DocumentListener and add it to your text field's document,
as in

 field.getDocument().addDocumentListener(docListener);

If it's sufficient to know that a change has taken place, and then the
result of the change, you can get that from the "insertUpdate" and
"removeUpdate" methods of DocumentListener, through the DocumentEvent. You
can then carry on with whatever processing you want.

If you need something more comprehensive, like on the fly input validation,
you're better off doing that that with JFormattedTextField (if it's
available to you) or by implementing your own Document type, where you can
override the "insertString" and "remove" methods to validation an operation
before committing it. Then, pass an instance of that Document into your text
component's constructor. It's probably easiest to subclass
javax.swing.text.PlainDocument, where you can add your custom code then
forward to super.whatever() for the model update.

For example, something like the following -- this document quietly prevents
any operation that result in the substring "FUN" appearing in the document.
I can't promise that this is the best way of doing this particular job, but
it makes the point about using these methods. To use it with a text field,
say

 field = new JTextField(new NoFunDoc(), "", 30);

public class NoFunDoc extends PlainDocument {
 public void insertString(int offs, String str, AttributeSet a)
     throws BadLocationException {
   StringBuffer buf = new StringBuffer(getText(0, getLength()));
   buf.insert(offs, str);
   if (buf.toString().toUpperCase().indexOf("FUN") != -1) {
     return;
   }
   super.insertString(offs, str, a);
 }
 public void remove(int offs, int len) throws BadLocationException {
   StringBuffer buf = new StringBuffer(getText(0, getLength()));
   buf.delete(offs, offs + len);
   if (buf.toString().toUpperCase().indexOf("FUN") != -1) {
     return;
   }
   super.remove(offs, len);
 }
}

Signature

Hope this does some good! Regards,
Sean.

Adam - 28 May 2004 11:36 GMT
Wow, excellent response, thanks!

Its being used in a search field, where the fields found starting with the
text so far are listed, which adding a documentListener is enough to do.

Cheers,

adam

> > Hi Adam,
> >
[quoted text clipped - 47 lines]
>   }
> }
Roedy Green - 26 May 2004 04:54 GMT
>I want to run a piece of code everytime the text in a JTextField changes. I
>have managed to detect a key press by adding a KeyListener, but if i call
>textField.getText(), it returns the previous value. How do I get the new
>text that will be there after this new keystroke is processed?

See JFormattedTextField that has an elaborate scheme to give you
intermediate results.

Signature

Canadian Mind Products, Roedy Green.
Coaching, problem solving, economical contract programming.
See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.