ScalaFX:查找子场景总是返回null
我有一个ScalaFX应用程序,它包含一个带有ScalaFX:查找子场景总是返回null,scala,user-interface,javafx,scalafx,Scala,User Interface,Javafx,Scalafx,我有一个ScalaFX应用程序,它包含一个带有场景和子场景的舞台。 我想要实现的就是在另一个范围内获得对子场景的引用(确切地说是一种方法),以便稍后更改子场景的内容。我的最小工作示例(不工作…)如下所示: object GuiTest extends JFXApp { def onClickByUser = { val subScene = stage.scene().lookup("sub").asInstanceOf[SubScene] println(subScene
场景
和子场景
的舞台。
我想要实现的就是在另一个范围内获得对子场景的引用(确切地说是一种方法),以便稍后更改子场景的内容。我的最小工作示例(不工作…)如下所示:
object GuiTest extends JFXApp {
def onClickByUser = {
val subScene = stage.scene().lookup("sub").asInstanceOf[SubScene]
println(subScene) // always null
}
stage = new PrimaryStage {
scene = new Scene(900, 900, true, SceneAntialiasing.Balanced) {
root = new BorderPane {
center = createView
}
}
}
def createView = {
new BorderPane {
center = new SubScene(800, 800, true, SceneAntialiasing.Balanced) {
id = "sub"
}
}
}
}
val javaSubScene = stage.scene().lookup("#sub").asInstanceOf[javafx.scene.SubScene]
val subScene = new SubScene(javaSubScene)
在这个简单的例子中,我添加了onClickByUser
方法,每当用户单击按钮时就会执行该方法(为了简单起见,上面没有显示按钮定义)-但是我总是得到null
,而不是子场景。为什么呢?谢谢你的帮助
编辑:
好吧,我忘了英镑符号(“#”):
但现在我明白了:
线程“JavaFX应用程序线程”中出现异常
java.lang.ClassCastException:javafx.scene.SubScene无法强制转换为
scalafx.scene.SubScene
如果我省略了[SubScene]的asInstanceOf[SubScene]
,那么它可以工作,但是返回的值的类型当然是节点
,而不是SubScene
edit2:
它的工作原理如下:
object GuiTest extends JFXApp {
def onClickByUser = {
val subScene = stage.scene().lookup("sub").asInstanceOf[SubScene]
println(subScene) // always null
}
stage = new PrimaryStage {
scene = new Scene(900, 900, true, SceneAntialiasing.Balanced) {
root = new BorderPane {
center = createView
}
}
}
def createView = {
new BorderPane {
center = new SubScene(800, 800, true, SceneAntialiasing.Balanced) {
id = "sub"
}
}
}
}
val javaSubScene = stage.scene().lookup("#sub").asInstanceOf[javafx.scene.SubScene]
val subScene = new SubScene(javaSubScene)
但在我看来,这有点难看,必须使用java类并创建新的scala包装器对象,而不仅仅是获取对现有对象的引用。。。欢迎任何改进。请使用
val subScene: scalafx.scene.SubSecne =
stage.scene().lookup("#sub").asInstanceOf[javafx.scene.SubScene]
您不需要手动将java子场景转换为scalafx版本,因为scala具有。要使用scalafx中定义的隐式,您需要使用importimport scalafx.Includes.\uu
顺便说一句,scalafx包装器就是这样转换它们的属性的。示例width
def width: scalafx.beans.property.ReadOnlyDoubleProperty = delegate.widthProperty