Views
2 months ago

tornadofx-guide

6. Type Safe CSS import

6. Type Safe CSS import javafx.scene.paint.Color import tornadofx.* class MyStyle: Stylesheet() { companion object { val tackyButton by cssclass() } private val topColor = Color.RED private val rightColor = Color.DARKGREEN private val leftColor = Color.ORANGE private val bottomColor = Color.PURPLE } init { tackyButton { rotate = 10.deg borderColor += box(topColor,rightColor,bottomColor,leftColor) fontFamily = "Comic Sans MS" fontSize = 20.px } } Now you can apply the tackyButton style to buttons, labels, and other controls that support these properties. While this styling can work with other controls like labels, we are going to target buttons in this example. First, load the MyStyle stylesheet into your application by including it as contructor parameter. class MyApp: App(MyView::class, MyStyle::class) { init { reloadStylesheetsOnFocus() } } The reloadStylesheetsOnFocus() function call will instruct TornadoFX to reload the Stylesheets every time the Stage gets focus. You can also pass the --livestylesheets argument to the application to accomplish this. Important: For the reload to work, you must be running the JVM in debug mode and you must instruct your IDE to recompile before you switch back to your app. Without these steps, nothing will happen. This also applies to reloadViewsOnFocus() which is similar, but reloads the whole view instead of just the stylesheet. This way, you can evolve your UI very rapidly in a "code change, compile, refresh" manner. 74

6. Type Safe CSS You can apply styles directly to a control by calling its addClass() function. Provide the MyStyle.tackyButton style to two buttons (Figure 6.2). class MyView: View() { override val root = vbox { button("Press Me") { addClass(MyStyle.tackyButton) } button("Press Me Too") { addClass(MyStyle.tackyButton) } } } Figure 6.2 Intellij IDEA can perform a quickfix to import member variables, allowing addClass(MyStyle.tackyButton) to be shortened to addClass(tackyButton) if you prefer. You can use removeClass() to remove the specified style as well. Targeting Styles to a Type One of the benefits of using pure Kotlin is you can tightly manipulate UI control behavior and conditions using Kotlin code. For example, you can apply the style to any Button by iterating through a control's children , filtering for only children that are Buttons, and applying the addClass() to them. class MyView: View() { override val root = vbox { button("Press Me") button("Press Me Too") } } children.asSequence() .filter { it is Button } .forEach { it.addClass(MyStyle.tackyButton) } 75

Guide
Guide
guide
guide to
guide
Guide
GUIDE
GUIDE
guide
GUIDE
GUIDE
guide
Guide
GUIDE TO
GUIDE
GUIDE
GUIDE
guide
Guide
Guide
Guide
Guide
GUIDE
Guide
GUIDE
GUIDE
The Guide
guiding
Guide
guide