我有一个fxml文件的控制器。控制器有一个字段public BorderPane mainBorderPane;
,它应该填充fxml文件中找到的相同fx:id
的Border窗格。当我尝试从内部类访问它时,它给出了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
根本没有分配引起的。 clearBorderPaneCenter
和clearBorderPaneRight
似乎没有崩溃,因为它们被try catch捕获。有关为什么mainBorderPane可能无法正确分配的任何想法?
您缺少fxml注释。 FXMLLoader需要将BorderPane注入代码中
@FXML
public BorderPane mainBorderPane;