edvin / tornadofx

Lightweight JavaFX Framework for Kotlin
Apache License 2.0
3.67k stars 269 forks source link

TornadoFX: How to display an icon in the tree correctly? #1265

Open aleksanderzagora opened 4 years ago

aleksanderzagora commented 4 years ago

Hello! I am an absolute newbie to Kotlin, IntelliJ and TornadoFX.

I figured out how to display the icon in the TreeView. But if I collapse the node, the icons disappear. What am I doing wrong?

image

MyApp.kt

import javafx.scene.control.TreeItem
import javafx.scene.control.TreeView
import tornadofx.*
import java.net.URI

fun main(args: Array<String>) {
    launch<Main>()
}

class Main : App(Workspace::class) {
    override fun onBeforeShow(view: UIComponent) {
        workspace.dock<testTreeView>()
    }
}

class testTreeView : View("TEST") {

    override val root = TreeView<Any>()

    init {
        with(root) {

            root = TreeItem<Any>("ROOT")

            cellFormat {
                text = when {
                    it.toString() == "ROOT" -> "ROOT"
                    else -> it.toString()
                }
                style {
                    graphic = when {
                        it == "ROOT" -> URI("root.png")
                        else -> URI("not_root.png")
                    }
                }
            }
            populate { parent ->
                val value = parent.value
                when {
                    value == "ROOT" -> listOf("Node1", "Node2")
                    else -> null
                }
            }
        }
    }
}

build.gradle

plugins {
    id 'org.jetbrains.kotlin.jvm' version '1.3.72'
    id 'application'
    id "org.openjfx.javafxplugin" version "0.0.9"
}

javafx {
    version = "11.0.2"
    modules = ['javafx.controls']
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
    maven { url = 'https://oss.sonatype.org/content/repositories/snapshots' }
    maven { url = 'https://dl.bintray.com/jerady/maven' }
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
    implementation "no.tornado:tornadofx:2.0.0-SNAPSHOT"
}

compileKotlin {
    kotlinOptions.jvmTarget = "11"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "11"
}
SKeeneCode commented 4 years ago

I was able to fix it by replacing:

style {
    graphic = when {
        it == "ROOT" -> URI("root.png")
        else -> URI("not_root.png")
    }
}

With

graphic = when {
     it == "ROOT" -> ImageView(Image("root.png"))
     else -> ImageView(Image("not_root.png"))
}

Your problem seems to be a result of a known bug that seems to be still unfixed in javaFX. Refer to this stackoverflow post and this bug report.