55

I would like to add a kind of listener to my JavaFX's TextField which when ever a user changes the value of the TextField, the Application prints something on the console.

I've searched and i find the following very similar question : Value Change Listener to JTextField

The answer of mentioned question is very clear and efficient, but unfortunately it is only useful for JTextField ( Not JavaFX's TextField) because it says you should use DocumentListener like this:

// Listen for changes in the text
textField.getDocument().addDocumentListener(new DocumentListener() {
  public void changedUpdate(DocumentEvent e) {
    warn();
  }
  public void removeUpdate(DocumentEvent e) {
    warn();
  }
  public void insertUpdate(DocumentEvent e) {
    warn();
  }

but in JavaFX's TextFields you are not able to do it. So? What is the solution?

(describing with code can be very good but if it is not possible, any hint will be appreciated)

Community
  • 1
  • 1
Elyas Hadizadeh
  • 3,289
  • 8
  • 40
  • 54

1 Answers1

133

Add a listener to the TextField's textProperty:

TextField textField = new TextField();
textField.textProperty().addListener((observable, oldValue, newValue) -> {
    System.out.println("textfield changed from " + oldValue + " to " + newValue);
});
Roland
  • 18,114
  • 12
  • 62
  • 93
  • 7
    This actually make the textfield lose focus, which is quite frustrating for users. – Dũng Trần Trung Mar 27 '17 at 09:02
  • 3
    For those of you using Kotlin, the above snippet looks like this: `val textField = TextField()` `textField.textProperty().addListener { observable, oldValue, newValue -> println("textfield changed from $oldValue to $newValue") }` – ATutorMe Apr 03 '18 at 07:33
  • 3
    Set focus in new Thread(() -> {Platform.runLater(() -> { . It's probably a bug. – Xdg Oct 24 '18 at 10:03