1
votes

I have the following code to define a tableview with specific cells changing color depending on condition.

How I can define a typesafe stylesheet class and apply it to current code preventing the duplication in future?

class MonitorView : View("Monitor") {
    override val root = borderpane {
        center = tableview<ServerModel> {
            items = readConfiguration().observable()
            readonlyColumn("Environment", ServerModel::env)
            readonlyColumn("Host", ServerModel::host)
            readonlyColumn("Port", ServerModel::port)
            readonlyColumn("Application Name", ServerModel::appName)
            column("Is online", ServerModel::isReachable).cellFormat {
                styleDependingOnBoolean(it)
                graphic = hbox {
                    button("Restart").action {
                        isDisable = true
                    }
                }
            }
        }
    }

private fun TableCell<ServerModel, Boolean>.styleDependingOnBoolean(it: Boolean) {
    if (it) {
        style = "-fx-background-color:#00b200; -fx-text-fill:white"
        text = it.toString()
    } else {
        style = "-fx-background-color:#8b0000; -fx-text-fill:white"
        text = it.toString()
    }
}

}

2

2 Answers

0
votes

If I understood correctly, you are looking for something like the following;

javafxNode.getStyleClass().add("myCssClass");
// passing true here will activate your css code below
javafxNode.pseudoClassStateChanged("myPseudoClass",yourBoolean);

In your CSS file:

.myCssClass:myPseudoClass{
     -fx-text-fill:white 
}
0
votes

You can create a type safe stylesheet and create a selector for this connectivity column which has the default background color. Then add another selector called reachable which overrides this color, like so:

class MyStyles : Stylesheet() {
    companion object {
        val reachable by cssclass()
        val connectivityColumn by cssclass()
    }

    init {
        connectivityColumn {
            backgroundColor += c("#8b0000")
        }
        connectivityColumn and reachable {
            backgroundColor += c("#00b200")
        }
    }
}

Make sure this column gets the connectivityColumn class, and toggle the reachable state using toggleClass:

column("Reachable", Server::reachableProperty) {
    addClass(MyStyles.connectivityColumn)
    cellFormat {
        toggleClass(MyStyles.reachable, item)
        graphic = hbox {
            button("Restart")
        }
    }
}

Note that this only updates the color when the tableview redraws. If you need to update the color based on external events when the tableview doesn't redraw, either fire an event to redraw it, or use a binding instead. If you get a way with the first approach I would recommend it as it doesn't attach any listeners.