How to add line breaks to prompt text in JavaFX?

Retronix :

I have a TextArea that has some prompt text that I want to be split onto a few different lines, however, line breaks don't work in prompt text for some reason.

Code:

TextArea paragraph = new TextArea();
paragraph.setWrapText(true);
paragraph.setPromptText(
    "Stuff done today:\n"
    + "\n"
    + "- Went to the grocery store\n"
    + "- Ate some cookies\n"
    + "- Watched a tv show"
);

Result:

enter image description here

As you can see, the text does not line break properly. Does anyone know how to fix this?

kleopatra :

The prompt is internally shown by a node of type Text which can handle line breaks. So the interesting question is why don't they show? Reason is revealed by looking at the promptText property: it is silently replacing all \n with empty strings:

private StringProperty promptText = new SimpleStringProperty(this, "promptText", "") {
    @Override protected void invalidated() {
        // Strip out newlines
        String txt = get();
        if (txt != null && txt.contains("\n")) {
            txt = txt.replace("\n", "");
            set(txt);
        }
    }
};

A way around (not sure if it is working on all platforms - does on my win) is to use the \r instead:

paragraph.setPromptText(
    "Stuff done today:\r"
    + "\r"
    + "- Went to the grocery store\r"
    + "- Ate some cookies\r"
    + "- Watched a tv show"
);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=96810&siteId=1