Ken Tsang
Ken Tsang

Reputation: 61

javafx label text color dynamic bindings

I have a label labelSign which is showing the +ve or -ve sign.

and I have another label labelValue and the text color of the label is depending on the text of labelSign.

This code is ok if there are two kinds of colors:

labelValue.textFillProperty().bind(Bindings.when(labelSign.textProperty().isEqualsTo("+ve")).then(Color.GREEN).otherwise(Color.RED));

How to handle if there are 3 cases of labelSign: +ve, -ve and empty and painting the text of labelValue as BLACK if the labelSign is empty?

Upvotes: 0

Views: 610

Answers (1)

fabian
fabian

Reputation: 82451

Use Bindings.createObjectBinding to create a binding with the text property as dependency.

private static Color textToColor(String text) {
    ...
}
labelValue.textFillProperty().bind(Bindings.createObjectBinding(() -> textToColor(labelSign.getText()), labelSign.textProperty());

This allows you to use an arbitrary algorithm to determine the color based on the text. An update happens everytime one of the dependencies (in this case the text property of the Label) is updated.

On the other hand you can set an arbitrary text color without changing the displayed result, if the text is empty (= empty string)...

Upvotes: 2

Related Questions