0

I want to detect when the string in a Text Field changes(both when chars are added and when chars are backspaced), to do so I tried using the onKeyTyped function

    SearchTF.onKeyTypedProperty(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            System.out.println("Hello World!");
        }
    });

This code does not work

So here are my three question

  1. Why does this not work
  2. How can I get this working
  3. Is there a better way to detect when a string in a Text Field changes? (As mentioned in the first line)
EltoCode
  • 65
  • 4

1 Answers1

0
myTextField.textProperty().addListener((object, oldValue, newValue) -> {
            if (newValue.length() > oldValue.length()) {
                System.out.println("letter add");
            } else {
                System.out.println("letter removed");
            }
        });
saw1k
  • 131
  • 1
  • 2
  • Thanks! is this the best practice when doing these things? – EltoCode Apr 19 '20 at 14:57
  • 2
    While this answer actually addresses the question as directly stated, it would probably end up not behaving the exact way the OP (or the users of his/her application) would want. There are more complex ways that text can change other than simply adding or removing one character at a time. E.g. if the text field contains `"abcd"`, and its all selected, and the user pastes (CTRL-V or mouse) in the string `"acdef"`, this code wouldn't capture the fact that a character (`"b"`) had been removed; there are many other similar scenarios. – James_D Apr 19 '20 at 18:01