0

我正在尝试在 FXML 定义的表单控制器中为动态创建的按钮编写事件处理程序,它似乎工作正常,但一旦我尝试访问另一个元素,它就会失败。

例如这段代码工作正常:

import java.util
import java.net.URL
import javafx.{scene => jfxs, fxml => jfxf}
import javafx.event.{EventHandler, ActionEvent}
import scalafx.Includes._

class  MainFormFxmlController extends jfxf.Initializable{
  @jfxf.FXML
  private var anchorPane: jfxs.layout.AnchorPane = _

  @jfxf.FXML
  private var slider: jfxs.control.Slider = _

  def initialize(url: URL, rb: util.ResourceBundle) {
    // the slider variable becomes null at this point if I observe it in the button event handler below and is not null id I don't
    slider.valueProperty.addListener{ (o: javafx.beans.value.ObservableValue[_ <: Number], oldVal: Number, newVal: Number) =>
      // ...
    }

    //...

    val button = new jfxs.control.Button("Button")

    jfxs.layout.AnchorPane.setRightAnchor(button, 63.0)

    jfxs.layout.AnchorPane.setTopAnchor(button, 14.0)

    anchorPane.getChildren.add(button)

   button.setOnAction(new EventHandler[ActionEvent]() {
      @Override
      def handle(event: ActionEvent) {
        println("123") // trying to access the slider variable here makes the whole app fail on load
      }
    })
  }
}

但是通过在函数开头抛出 NullPointerException 来替换println("123")就足以if(slider != null) println("123")使应用程序失败。initialize

我想要达到的是调整按钮按下时的滑块值(同时创建这个特定的按钮动态地从 FXML 加载表单的其余部分),我认为我的错误是使用了错误的方法来做到这一点,但我已经发现仅对滑块变量进行的空检查会导致失败,不一定是其值调整。

这对我来说看起来很奇怪,好像滑块变量为空我会通过检查得到这个事实,如果它无法访问,应用程序将无法编译,但我得到的是不同的。

4

0 回答 0