我正在尝试使其可以从另一个选项卡中为我的 TabPane 创建一个新选项卡,但我遇到了一些困难。目前,我在“main-window.fxml”中设置了 TabPane 和相应的 MainWindowController。我在此 TabPane 中有一个选项卡,它通过 fx:include 将“mainTab.fxml”显示到场景图,由 MainTabController 控制。现在,从“mainTab”中,我希望有一个按钮能够向 TabPane 添加附加选项卡,但由于这需要引用“main-window”中的 TabPane,因此我在“main-”中创建了一个静态方法 window ”。当运行下面的代码时,我在 MainWindowController 中的这一行收到 NullPointerException:
mainTabPane.getTabs().add(new Tab(team.getTeamName()));
有人可以告诉我为什么会出现此异常以及我如何开始解决它吗?
主窗口.fxml:
<TabPane fx:id="mainTabPane">
<tabs>
<Tab fx:id="mainTab" text="Main" closable="false">
<fx:include source="mainTab.fxml" fx:id="mainWindowTab" alignment="CENTER"/>
</Tab>
</tabs>
</TabPane>
mainTab.fxml(按钮的事件处理程序):
@FXML
public void handleSubmit() {
String teamName = teamNameTextField.getText();
Roster roster = rosterComboBox.getValue();
int startWeek = spinner.getValue();
Team newTeam = new Team(teamName, startWeek, roster);
TeamData.addTeam(newTeam);
MainWindowController controller = new MainWindowController();
controller.createTeamTab(newTeam);
}
主窗口 Controller :
public class MainWindowController {
@FXML
private TabPane mainTabPane;
public void createTeamTab(Team team) {
mainTabPane.getTabs().add(new Tab(team.getTeamName()));
}
}
最佳答案
您的代码不起作用,因为您没有在 Controller 上调用 createTeamTab(...)
:您正在您创建的 MainWindowController
的另一个实例上调用它。 (加载 FXML 时,@FXML
注释的字段由 FXMLLoader
在 Controller 实例中初始化:出于相当明显的原因,它们不会在任意情况下设置为相同的值。同一类的其他实例。)您需要获取对用于主选项卡的 Controller 的引用,并将其传递给主 Controller 的引用。
您没有告诉我们 mainTab.fxml
Controller 的类名称:我假设它是 MainTabController
(所以只需将其更改为您想要的任何类名称)实际使用)。
在MainWindowController
中,执行:
public class MainWindowController {
@FXML
private TabPane mainTabPane;
@FXML
// fx:id of the fx:include with "Controller" appended
private MainTabController mainWindowTabController ;
public void initialize() {
mainWindowTabController.setMainWindowController(this);
}
public void createTeamTab(Team team) {
mainTabPane.getTabs().add(new Tab(team.getTeamName()));
}
}
然后在MainTabController
中执行
public class MainWindowController {
private MainWindowController mainWindowController ;
public void setMainWindowController(MainWindowController mainWindowController) {
this.mainWindowController = mainWindowController ;
}
@FXML
public void handleSubmit() {
String teamName = teamNameTextField.getText();
Roster roster = rosterComboBox.getValue();
int startWeek = spinner.getValue();
Team newTeam = new Team(teamName, startWeek, roster);
TeamData.addTeam(newTeam);
mainWindowController.createTeamTab(newTeam);
}
}
关于JavaFX:从选项卡 Controller 添加新选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44111927/