首页 > 解决方案 > 根据单击的按钮将选项卡添加到 TabPane

问题描述

我有一个名为Home.fxml的文件,它是一个BorderPane. 该组件左侧有按钮,中间有一个空的 TabPane mainTabPane。我想,当用户单击左侧的任何按钮时,将选项卡添加到mainTabPane. 单击一个按钮时,我可以添加一个选项卡。但是当我尝试对第二个按钮做同样的事情时,我得到了这个错误:

java.lang.IllegalStateException: Location not set

这是 HomeController.java 的代码,所有的都在这里完成:

public void initialize(URL loc, Resource Rse) {
    createReportsTab();
    loadCreateItemTab();
}

/*this is the one which works well*/
@FXML
void CreateReportTab() { 
    FXMLLoader loader = new FXMLLoader(); 
    loader.setLocation(ReportsController.class.getResource("gui/Reports.fxml"));
    Parent parent = loader.load(); 
    Tab reportsTab = new Tab("Reporting Engine");
    reportsTab.setClosable(true);
    reportsTab.setcontent(parent);
    mainTabPane.getTabs().add(reportsTab),
}

/*this is the one which produces the error*/
@FXML
void loadCreateItemTab() { 
    FXMLLoader loader = new FXMLLoader(); 
    loader.setLocation(AddNewItemController.class.getResource("gui/addNewItem.fxml"));
    Parent parent = loader.load(); 
    Tab newItemTab= new Tab("New Item");
    newItemTab.setClosable(true);
    newItemTab.setcontent(parent);
    mainTabPane.getTabs().add(newItemTab),
}

我很困惑; 为什么报告引擎加载良好,但第二个却产生了上面的错误?

这是我在 IntelliJ IDEA 中的项目结构:

在此处输入图像描述

所有控制器类都在控制器包中,所有 FXML 文件都在 GUI 包中。主类在 Companion 包中。

标签: javafx

解决方案


错误提示未读取addNewItem.fxml 。改变:

AddNewItemController.class.getResources("gui/addNewItem.fxml");

ReportsController.class.getResources("gui/addNewItem.fxml");

,因为这条路已经为你工作了。


推荐阅读