JTextField: can't listen when the text is changed

F

Federico

Hello,

I'm fighting with a JTextField and don't find how to call getText
everytime the text is changed. I tried the code shown below
(automatically generated by NetBeans) but it does nothing (never prints
"Hola").

I tried to add a KeyListener for keyTyped and it works but when I call
getText the last key typed is not there.

Do you know what happens?
(I'm working on a Mac OSX with java 1.4.2_05)

Thanks in advance,
Federico



jTextField1.addInputMethodListener(new
java.awt.event.InputMethodListener() {
public void
inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
jTextField1InputMethodTextChanged(evt);
}
public void
caretPositionChanged(java.awt.event.InputMethodEvent evt) {
jTextField1CaretPositionChanged(evt);
}
});

private void jTextField1InputMethodTextChanged(
java.awt.event.InputMethodEvent evt) {
// TODO add your handling code here:
System.err.println("Hola");
}
 
F

Federico

I found the solution in an old message:


Autor:Mark McMillan ([email protected])
Asunto:Re: Event when text is changed in TextField
Fecha:2000/06/13

You want to listen for changes on the Document that is associated
with the TextField. If you don't explicitly create a Document the
TextField does it for you. To setup a listener:

// Listen for changes in the text
myTextField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
// text was changed
}
public void removeUpdate(DocumentEvent e) {
// text was deleted
}
public void insertUpdate(DocumentEvent e) {
// text was inserted
}
});

Note this works no matter how the text gets changed; via a
clipboard cut/paste, progamatic "setText()" on the TextField,
or the user typing into the field on the UI.

Hope this helps,
-Mark McMillan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top