> 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
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]
> }
> }