如何在 ScalaFX 中动态添加节点到 VBox

How to dynamically add Nodes to VBox in ScalaFX

我的 ScalaFX 应用程序有一个 Button,它将 GridPane 添加到 VBox。我尝试直接更新 Button.onAction 中的 VBox 子级,但这会导致 Button 在呈现第一个添加的 GridPane 后变得无响应。我现在正在尝试以下代码:


import scalafx.scene.{Node, Scene}
import scalafx.application.JFXApp
import scalafx.geometry.Insets
import scalafx.scene.control.{Button, Label}
import scalafx.scene.layout.{GridPane, VBox}
import scalafx.Includes._
import scalafx.collections.ObservableBuffer

object Gui extends JFXApp {

  stage = new JFXApp.PrimaryStage {
    title = "DSP Lab"
    scene = new Scene(320, 300) {

      val bufferOfNodes = new ObservableBuffer[Node]

      val vBox = new VBox {
        children = bufferOfNodes // assign ObservableBuffer to children
      }

      val addGridPaneButton = new Button {
        text = "Add GridPane to VBox"
        onAction = _ => {
          bufferOfNodes += getNewGridPane // update the ObservableBuffer
        }
      }

      content = List(addGridPaneButton, vBox)
    }
  }

  stage.setX(100)
  stage.setY(100)

  def getNewGridPane: GridPane = new GridPane {
    vgap = 5
    hgap = 10
    padding = Insets(20)

    val sampleFrequencyLabel = new Label("Sample Frequency:")
    val sampleFrequencyField = new DoubleField
    val amplitudeLabel = new Label("Amplitude:")
    val amplitudeField = new DoubleField
    add(sampleFrequencyLabel, 0, 0)
    add(sampleFrequencyField, 1, 0)
    add(amplitudeLabel, 0, 1)
    add(amplitudeField, 1, 1)
  }
}

通过将 VBox.children 分配给 ObservableBuffer[Node]Button 保持响应,onActionGridPane 添加到 bufferOfNodes,但 GridPanes 似乎永远不会被添加到 VBox 并且它们永远不会被渲染。

有办法吗?

这是在 ScalaFX-Users 邮件列表中被询问和回答的: https://groups.google.com/forum/?utm_medium=email&utm_source=footer&pli=1#!topic/scalafx-users/3IzGAnflUnU