6

I am trying to write to a JavaFX label. I can write successfully and use wrapping to make sure the text wraps to a new line if it is longer than the label. My issue is I need to add text to the existing text which I can do, but I am unable to make the next text start on a new line.

Any help would be appreciated.

user3325416
  • 75
  • 1
  • 1
  • 6

3 Answers3

9

I have been looking for multiline label trick in FXML for some time and many times I visited this post (google displayed this result, a lot of frustration). So I think I will write it here.

I managed to find this code to display multiline:

<Label text="${'number of registered\nreaders'}"/>

But if I define variable

<fx:define>
    <String fx:id="LABEL_01" fx:value="${'number of registered\nreaders'}"/> 
</fx:define>

then I have no idea how to refer to it, I can't use $LABEL_01.


In FXML you can also use this: '&#xD;'. Then this code works:

<fx:define>
    <String fx:id="LABEL_01" fx:value="number of registered&#xD;readers"/> 
</fx:define>

And you can use LABEL_01 like this:

<Label text="$LABEL_01"/>
Pochmurnik
  • 780
  • 6
  • 18
  • 35
  • regarding `$LABEL_01`, binding expressions dont have variable shorthand, so `${LABEL_01}` will work – Groostav Oct 09 '19 at 21:53
7

Just add a newline character:

Label label = new Label();
label.setText("Hello\nWorld");
James_D
  • 201,275
  • 16
  • 291
  • 322
0

You can try something like:

 yourlabel.setText(yourLabel.getText() + System.lineSeparator() + "New String");
Baptiste Beauvais
  • 1,886
  • 1
  • 12
  • 19