出于某种原因,我无法将 FXML 文件中定义的节点加载到我的实例变量中。我制作了这两个测试文件:
测试.java:
public class Test extends Application {
@FXML private TextArea ta;
@FXML private Label l;
public void start(Stage primaryStage) {
Scene scene = null;
try {scene = new Scene((BorderPane)FXMLLoader.load(Test.class.getResource("ChatServer.fxml")));}
catch (IOException e) {}
primaryStage.setScene(scene);
primaryStage.setTitle("Chat Server");
primaryStage.show();
System.out.println(ta);
System.out.println(l);
}
}
FXML 文件:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.text.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="400.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Test">
<top>
<Label fx:id="l" text="text" BorderPane.alignment="CENTER">
<BorderPane.margin>
<Insets bottom="10.0" top="10.0" />
</BorderPane.margin>
<font>
<Font size="13.0" />
</font>
</Label>
</top>
<center>
<TextArea fx:id="ta" editable="false" focusTraversable="false" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER" />
</center>
</BorderPane>
两者都是TextArea
和 Label
打印为 null
当它们应该被注入(inject) FXML 文件中定义的节点时,有人知道这里出了什么问题吗?当我在场景生成器中编辑 FXML 文件时, Controller 类和字段都会被找到并识别,因此应该不会有任何问题。
最佳答案
FXMLLoader.load 创建 Test 类的新实例。 所以这将与您当前的类(class)不同。
使用 FXMLLoader 类的 setControllerFactory 方法来更改此行为。
关于JavaFX - 无法从 FXML 文件加载节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36011095/