【发布时间】:2021-03-04 16:02:42
【问题描述】:
当我声明一个现场播放器时,如下所示:
class Controller{
@FXML Shape player;
}
.fxml 文件 - <Rectangle fx:id="player" ...\>
其中Controller,player被声明为超类型(Shape),在fxml文件中
它被声明为子类型。
我将播放器声明为 Shape,而不是 Rectangle,因为我有多个类似的 fxml 文件,并且程序会在运行时决定加载哪个文件。每个 fxml 文件都有一个 Shape 子类的播放器对象
我的问题是,当一个字段被声明为超类型时,fxml 加载器不会初始化该字段。我想知道这个问题的解决方法。
一个最小可重现的例子:
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.shape.Shape;
import javafx.stage.Stage;
public class test2 extends Application {
@FXML Shape player;
public void start(Stage stage) throws Exception
{
Scene scene = new Scene(
FXMLLoader.load(getClass().getResource("t.fxml"))
);
stage.setTitle("JavaFX Example");
stage.setScene(scene);
stage.show();
System.out.println(player); //prints null
}
public static void main (String [] args){
launch(args);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.shape.Rectangle?>
<Pane xmlns:fx="http://javafx.com/fxml" prefHeight="400.0" prefWidth="600.0">
<Rectangle fx:id="player" x="20" y="20" width="40" height="40"/>
</Pane>
【问题讨论】:
-
该字段在控制器中初始化,而不是在
Applicaation实例中。你甚至没有在 FXML 中声明一个控制器类。 -
我的问题是,当一个字段被声明为超类型时,fxml 加载器不会初始化该字段你确定吗?如果定义为
Rectangle player,是否初始化? -
另外,
Controller不是您在问题中发布的任何内容的超类型... -
对不起。这不是因为使用了超类型。但我无法初始化程序中的字段。找到原因后我会编辑问题
-
另外:“我有多个类似的 fxml 文件,程序在运行时决定加载哪个文件”。每个 FXML 文件应该有一个不同的控制器类。