mauretto
mauretto

Reputation: 3212

JavaFX - Label text color on negative text value

I would like to change text color of my Label in case its text value is a negative number (or starts with a '-'). Is there a proper binding to make it works?

Upvotes: 0

Views: 250

Answers (1)

fabian
fabian

Reputation: 82461

No, you need to create it yourself, e.g.

Label label = ...
IntegerExpression value = ...

label.textProperty().bind(value.asString());
label.textFillProperty().bind(Bindings.when(value.lessThan(0))
                                      .then(Color.RED)
                                      .otherwise(Color.BLACK));

If you've don't have a expression that allows you to create a condition in this way you could of course also create a binding that depends on the Label's text property:

Label label = ...
label.textFillProperty().bind(Bindings.createObjectBinding(() -> label.getText().startsWith("-")
                                                                 ? Color.RED
                                                                 : Color.BLACK,
                                                           label.textProperty()));

Upvotes: 2

Related Questions