Search code examples
javajavafxuser-experience

JavaFX display text area appending - any way to highlight/make new text more visible?


I have a display text area in my JavaFX app.

It has several methods for appending strings to it.

What I want is for any newly appended text to have some kind of feedback so the user is more visually aware of the new text being displayed.

Ideally what I would like is one of the following, but am very open to other suggestions:

  • The appended text is 'typed out' as if someone were typing it into the display text area itself. Or..
  • Some kind of highlighting of the new text as it appears.

Although again, I'm open to suggestions!

Thank you.


Solution

  • As suggested in Highlighting Strings in JavaFX TextArea, you can select the new text.

    Assuming the text area is not editable, and you are only ever appending to the end of the existing text, you can do:

    textArea.textProperty().addListener((obs, oldText, newText) -> {
        if (newText.length() > oldText.length()) {
            Platform.runLater(() ->
                textArea.selectRange(oldText.length(), newText.length()));
        }
    });
    

    If your text area is editable, or you are using it more generally, then you can do something similar each time you append text. For example:

    String message = ... ;
    textArea.positionCaret(textArea.getLength());
    textArea.appendText(message);
    textArea.extendSelection(textArea.getLength());