这可能是导频错误,但FXML属性未绑定到fx:id上的控制器类。我把它简化为一个微不足道的例子,但仍然没有快乐"。我在俯瞰什么?
FXML文件......
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.BorderPane?>
<BorderPane fx:id="mainFrame" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.controller.BorderPaneCtrl">
<left>
<AnchorPane fx:id="anchorPaneLeft" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER" />
</left>
</BorderPane>
相关的Java代码是......
package sample.controller;
import javafx.fxml.FXML;
import javafx.scene.layout.AnchorPane;
public class BorderPaneCtrl {
@FXML private AnchorPane anchorPaneLeft;
public BorderPaneCtrl() {
/* so, @FXML-annotated variables are accessible, but not
* yet populated
*/
if (anchorPaneLeft == null) {
System.out.println("anchorPaneLeft is null");
}
}
/* this is what was missing...added for "completeness"
*/
@FXML
public void initialize() {
/* anchorPaneLeft has now been populated, so it's now
* usable
*/
if (anchorPaneLeft != null) {
// do cool stuff
}
}
自我在这里不是问题,我很确定我忽略了一些简单的事情。
答案 0 :(得分:1)
FXML元素尚未在constuctor中分配,但您可以使用Initializable接口,其中已经分配了元素。
public class Controller implements Initializable {
@FXML
AnchorPane anchorPaneLeft;
public Controller() {
System.out.println(anchorPaneLeft); //null
}
@Override
public void initialize(URL location, ResourceBundle resources) {
System.out.println(anchorPaneLeft); //AnchorPane
}
}
我假设您知道应该使用FXML创建控制器,例如:FXMLLoader.load(getClass().getResource("sample.fxml");