I have a JTextField.
I want to invoke a function when the text in it is changed.
How do I do that?
I have a JTextField.
I want to invoke a function when the text in it is changed.
How do I do that?
The appropriate listener in Java's swing to track changes in the text content of a JTextField is a DocumentListener, that you have to add to the document of the JTextField:
myTextField.getDocument().addDocumentListener(new DocumentListener() {
// implement the methods
});
Use Key Listener in this way
JTextField tf=new JTextField();
tf.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent ke)
{
if(!(ke.getKeyChar()==27||ke.getKeyChar()==65535))//this section will execute only when user is editing the JTextField
{
System.out.println("User is editing something in TextField");
}
}
});
You can use Caret Listener
JTextField textField = new JTextField();
textField.addCaretListener(new CaretListener() {
@Override
public void caretUpdate(CaretEvent e) {
System.out.println("text field have changed");
}
});
You can add a KeyListener or a ActionListener to the field and capture events.