应该由 fxml 分配的字段在从内部类 - javaFX 访问时抛出 NullPointerException



我有一个用于 fxml 文件的控制器。控制器有一个字段public BorderPane mainBorderPane;该字段应该用 fxml 文件中相同fx:id的"边框"窗格填充。当我尝试从内部类访问它时,它会给出NullPointerExcetion

clearBorderPaneCenter();clearBorderPaneRight工作得很好,但是当我运行cashSceneController.show()时,它会在线上崩溃mainBorderPane.setRight(rightLayout);

fxml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.image.*?>
<?import java.net.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.text.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<BorderPane fx:id="mainBorderPane" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Program.gui.MainSceneController">
<top>
<Pane prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER" />
</top>
<left>
<Pane prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER" />
</left>
<center>
<Pane prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER" />
</center>
<right>
<Pane prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER" />
</right>
<bottom>
<Pane prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER" />
</bottom>
</BorderPane>

控制器的简化版本:

public class MainSceneController {
MainSceneController.CashSceneController cashSceneController = new MainSceneController.CashSceneController();
public BorderPane mainBorderPane;
public void switchLayout(byte ID){
//todo Make this work switchScene()
clearBorderPaneCenter();
clearBorderPaneRight();
cashSceneController.show();
}
public void clearBorderPaneRight(){
try {
mainBorderPane.setRight(null);
OutputHelper.log("cleared right of mainBorderPane");
} catch (Exception e){
OutputHelper.log("clearing right of mainBorderPane not required - already cleared");
}
}
public void clearBorderPaneCenter(){
try {
mainBorderPane.setCenter(null);
OutputHelper.log("cleared centre of mainBorderPane");
} catch (Exception e){
OutputHelper.log("clearing centre of mainBorderPane not required - already cleared");
}
}
public class CashSceneController{
VBox rightLayout;
public void show() {
setVBox();
mainBorderPane.setRight(rightLayout);
}
public void setVBox(){
rightLayout = new VBox();
//......
}
}
}

这就是 fxml 文件的加载方式

SceneController = new MainSceneController(new Scene(FXMLLoader.load(getClass().getResource("gui/MainScreen.fxml"))));

我希望我能很好地解释我的问题。我是堆栈溢出的新手,不知道什么是好问题

编辑:问题似乎是由根本没有分配mainBorderPane引起的。clearBorderPaneCenterclearBorderPaneRight似乎没有崩溃,因为它们被尝试捕获了。任何想法为什么主边框窗格可能无法正确分配?

您缺少 fxml 注释。FXMLLoader 需要将边框窗格注入到代码中

@FXML      
public BorderPane mainBorderPane;

最新更新