tornadofx使用barchart、AnimationTimer、timeline動畫演示分錢問題

演示地址:https://www.bilibili.com/video/av59397164java

import javafx.animation.AnimationTimer
import javafx.collections.FXCollections
import javafx.scene.chart.CategoryAxis
import javafx.scene.chart.NumberAxis
import javafx.scene.chart.XYChart
import javafx.scene.paint.Color
import javafx.scene.shape.Rectangle
import javafx.util.Duration
import tornadofx.*

class LearnApp : App(LearnV::class)
class LearnV : View("learn 分錢問題") {
    //    100個矩形容器
    val rec = FXCollections.observableArrayList<Rectangle>()
    val b = (0..99)
    val money0 = 50
    //    100我的,每人money0元
    val money = b.map { money0 }.toIntArray()
    //    動畫計時器
    val aniTimer = AniTimer(this)
    //    每次給其餘人10元
    val money1 = 10
    val result = stringProperty()
    val max = stringProperty()
    val h = doubleProperty()
    lateinit var data0: XYChart.Data<String, Number>
    val datas = FXCollections.observableArrayList<XYChart.Data<String, Number>>()

    override val root = borderpane {
        top = vbox(5) {
            label(result) {
                isWrapText = true
            }
            label(max)
            hbox(5) {
                button("run").action {
                    //                ani()
                    aniTimer.start()
                }
                button("stop").action {
                    //                ani()
                    aniTimer.stop()
                }
            }
        }
        center = group {
            barchart("分錢問題", CategoryAxis(), NumberAxis(-200.0, 200.0, 10.0)) {
                series("Product X") {
                    (1..100).forEach {
                        data0 = data("${it}", 100)
                        datas.add(data0)
                    }
                    barGap = 0.01

                }
                categoryGap = 5.0
                prefHeight = 800.0
                prefWidth = 1600.0
            }
        }
    }

    fun paint() {
        var i = 0
        timeline {
            keyframe(Duration.seconds(0.010)) {
                money.forEach {
                    val j = b.random()
                    //        保證每人手裏有錢
                    money[i] -= money1
                    money[j] += money1
                    keyvalue(datas[i].YValueProperty(), money[i])
                    keyvalue(datas[j].YValueProperty(), money[j])
                    i++
                }
//                如要看排序後的結果,取消下面註釋
                money.sort()
                result.value = money.toList().toString()
                max.value = "最大值:${money.max()}"
            }
        }
    }


    // 此方法能夠中止動畫
    class AniTimer(val learnV: LearnV) : AnimationTimer() {
        var lastTime = 0L
        override fun handle(now: Long) {
            if ((now - lastTime) > 10000000) {
                lastTime = now
            } else {
                return
            }
            learnV.paint()
        }
    }
}
相關文章
相關標籤/搜索