Wulf
Wulf

Reputation: 393

Binding boolean (Property) to List operations in JavaFX

I found JavaFX to be suprisingly expressive after getting over the fact that I had to redeclare every field as property so I am a little stumped and would like to know if there is a better, more idomatic way of binding a boolean to some more complex operation like adding and removing style classes.

In this example I have a project that maybe valid or not and I want the font color of the tab to indicate which it is. I am doing this by adding and removing the error style class:

    val errorSwitch = { valid : Boolean ->
        logger.debug {"errorSwitcher: $valid"}
        if( valid) tab.styleClass.remove("error")
        else tab.styleClass.add("error")
        Unit
    }
    product.isValid.onChange (errorSwitch)
    errorSwitch(product.isValid.value)

What I don't like here is that I have to call the function once myself to start with because "onChange" obviously does not trigger unless the isValid actually changes. It's a small thing but I am wondering if there isn't a better way with bindings because thats what I want: the presence of the error class should be bound to "isValid"

Upvotes: 1

Views: 537

Answers (1)

Edvin Syse
Edvin Syse

Reputation: 7297

In TornadoFX the best way to achieve this is to use the toggleClass function, which will automatically add or remove a given class based on a boolean observable value. Therefore you can simply say:

tab.toggleClass(Styles.error, product.isValid)

This example requires you to use the Type Safe CSS feature of TornadoFX. Read more about Type Safe CSS in the guide :)

Upvotes: 3

Related Questions