Refer to a multiline String variable from fx:define block

Urle :

I defined multiline String variable in fx:define:

<fx:define>
    <String fx:id="LABEL_01" fx:value="${'liczba czytelników\nzarejestrowanych'}"/>
</fx:define>

Now I wish to refer to it in Label. How to do this using LABEL_01 as a text value? This doesn't work:

<Label text="$LABEL_01"/>

Wish to mention that this piece of code works:

<Label text="${'liczba czytelników\nzarejestrowanych'}"/>

Java code also works (why shouldn't it?):

Label labelLiczbaCzytelnikowZarejestrowanych = new Label("liczba czytelników\nzarejestrowanych");

but I want do it in FXML.

Slaw :

Wish to mention that this piece of code works:

<Label text="${'liczba czytelników\nzarejestrowanych'}"/>

This probably isn't working like you think it is.

The ${} syntax is an expression binding. This binds the target property (text) to the expression between the {}. As your expression is a 'string' you are using a string constant. When parsing the expression it will interpret the \n as a newline character. Basically, a string constant is treated the same as a string literal in Java code.

Note: You can see the text property is bound by injecting the Label into a controller and querying textProperty().isBound().

Some equivalent Java code would be:

Label label = new Label();
label.textProperty()
        .bind(Bindings.createStringBinding(() -> "liczba czytelników\nzarejestrowanych"));

<String fx:id="LABEL_01" fx:value="${'liczba czytelników\nzarejestrowanych'}"/>

The ${} syntax has no special meaning in the context of fx:value. What this does is create the target type (String) using the class' static valueOf(String) method. The argument for the valueOf method is the literal value as defined by the fx:value attribute. This means the expression binding syntax and the \n are used as is. The \n is literally a backslash followed by an "n", same as using "\\n" in Java.


An FXML file is, at its core, just an XML file. As far as I can tell, the FXML format provides no special multi-line support outside of string constants in an expression binding. However, you can use XML escapes to insert newline characters (i.e. your solution).

Guess you like

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