我有三层 根布局,主页,内容(rootLayout.fxml,home.fxml和content.fxml)
FXMLLoader loader = new FXMLLoader();
loader.setLocation(GenerateReport.class
.getResource("/skin/rootLayout.fxml"));
rootLayout = (AnchorPane) loader.load();
Scene scene = new Scene(rootLayout);
FXMLLoader loader = new FXMLLoader();
loader.setLocation(GenerateReport.class
.getResource("/skin/home.fxml"));
AnchorPane homeLayout = (AnchorPane) loader.load();
rootLayout.getChildren().addAll(homeLayout);
.
.
.
rootLayout.getChildren().addAll(contentLayout);
像这样我正在添加内容布局。在rootLayout.fxml中我有一个主页按钮。我的要求是用户点击主页按钮
然后我希望删除内容布局并使家庭布局可见。
content.fxml
< AnchorPane id =“myContent”... fx:controller =“com.ReportController”>
rootLayout.fxml
< AnchorPane id =“AnchorPane”.. fx:controller =“com.ReportController”>
<的子>
< Button fx:id =“home”onAction =“#homeBtn”... />
< /儿童>
< / AnchorPane>
在我的控制器中(在所有指向同一控制器的fxml文件中)我创建的类</ p>
@FXML
private Button home;
@FXML
private AnchorPane myContent;
@FXML
protected void homeBtn(ActionEvent event) throws Exception {
System.out.println("click! homeBtn");
myContent.getChildren().clear();
}
我面临的问题是我得到NullPointerException。即myContent.getChildren()返回null。任何人都可以帮我解决这个问题。
答案 0 :(得分:0)
你得到一个空指针异常,因为Javafx没有将你的myContent
与存储在fxml中的AnchorPane相关联,也没有附加对该对象的引用。
使用fx:id
为fxml文件中的节点指定其名称标识符。请注意,例如,您的@FXML private Button home
在fxml中标记为<Button fx:id="home"...>
。
在这种情况下,您的@FXML AnchorPane myContent
在fxml中标记为<AnchorPane id="myContent"...>
,而不是<AnchorPane fx:id="myContent"...>
。
id=""
仅用于CSS。