How do I add line breaks to hint text in JavaFX?… here is a solution to the problem.
How do I add line breaks to hint text in JavaFX?
I
have a TextArea with some hint text and I want to break it into several lines, but, for some reason, line breaks don’t work in the hint text.
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:
As you can see, the text does not wrap correctly. Does anyone know how to fix this?
Solution
Hints are displayed internally by a node of type text that can handle line breaks. So the interesting question is why don’t they show? You can reveal why by looking at the promptText property: it is silently replacing all \n
with an empty string:
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);
}
}
};
One workaround (not sure if it works on all platforms – I won) is to use \r
instead of:
paragraph.setPromptText(
"Stuff done today:\r"
+ "\r"
+ "- Went to the grocery store\r"
+ "- Ate some cookies\r"
+ "- Watched a tv show"
);