英文:
How to add a button to the view dynamically?
问题
我是 Kotlin 和 TornadoFX 的新手。也许我在 TornadoFX 中错过了一些非常基本的东西。我想要从一个可变的列表中创建按钮,并在视图中显示它们。如果用户点击添加按钮,列表应该获得一个新项,这将导致视图中出现一个新按钮。
谢谢你的帮助。
我认为代码应该如下所示:
import tornadofx.*
fun main(args: Array<String>) {
launch<MyApp>(args)
}
class MyApp: App(MainView::class)
class MainView: View("MainView") {
val values = ArrayList<Int>(listOf(1,2,3)).asObservable()
var count = 4
override val root = vbox {
values.onChange {
// Clear the view and recreate buttons when the list changes
this.clear()
values.forEach { x ->
button(x.toString())
}
button("add") {
action {
values.add(count)
println(values.toString())
count++
}
}
}
}
}
这段代码会生成这个视图,但如果我点击按钮,视图不会刷新。我认为我可能对绑定有所遗漏。
英文:
I'm new to Kotlin and TorandoFX. Maybe I'm missing something very basic in TornadoFX. I want to create from a list (which shoulde be mutable) buttons in the view. If the user clicks on the add button the list should get a new item and this should result in a new button in the view.
Thank you for your help.
I was thinking it should look like this:
import tornadofx.*
fun main(args: Array<String>) {
launch<MyApp>(args)
}
class MyApp: App(MainView::class)
class MainView: View("MainView") {
val values = ArrayList<Int>(listOf(1,2,3)).asObservable()
var count = 4
override val root = vbox {
values.forEach { x ->
button(x.toString())
}
button("add") {
action {
values.add(count)
println(values.toString())
count++
}
}
}
}
this code result in this view, but if I click the button the view doesnt refresh.
This code result in this view, but if I click the button the view doesnt refresh. I think I'm missing something about binding.
答案1
得分: 0
我们弄清楚了,我在绑定部分是正确的。我只需要使用 bindChildren()
函数,并将一个可观察数组和一个用于数组元素转换的函数作为参数传递。
感谢你的帮助。
import javafx.collections.FXCollections
import tornadofx.*
fun main(args: Array<String>) {
launch<MyApp>(args)
}
class MyApp: App(MainView::class)
class MainView: View("MainView") {
val values = FXCollections.observableArrayList<Int>(listOf(1,2,3))
var count = 4
override val root = vbox {
vbox {
bindChildren(values) { x ->
button(x.toString())
}
}
vbox() {
button("add") {
action {
values.add(count)
count++
}
}
}
}
}
英文:
We figured out, I was right with the binding part. I just had to use bindChildren()
function and give the function an observableArray and a function to for the conversion of the elements of the array as a parameter.
Thank you for the help.
import javafx.collections.FXCollections
import tornadofx.*
fun main(args: Array<String>) {
launch<MyApp>(args)
}
class MyApp: App(MainView::class)
class MainView: View("MainView") {
val values = FXCollections.observableArrayList<Int>(listOf(1,2,3))
var count = 4
override val root = vbox {
vbox {
bindChildren(values) { x ->
button(x.toString())
}
}
vbox() {
button("add") {
action {
values.add(count)
count++
}
}
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论