How to create tabs dynamically in JavaFX using FXML?

一曲冷凌霜 提交于 2019-12-05 21:30:00

You have already given the answer: just create a new tab and add it to the tab pane:

Tab tab = new Tab();
tabPane.getTabs().add(tab);

Complete example:

AddTabsExample.fxml:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.control.TabPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.control.Button?>

<BorderPane xmlns:fx="http://javafx.com/fxml/1"
    fx:controller="AddTabsController">
    <center>
        <TabPane fx:id="tabPane" />
    </center>
    <bottom>
        <HBox alignment="center">
            <Button text="Add tab" onAction="#addTab" />
            <Button text="List tabs" onAction="#listTabs" />
        </HBox>
    </bottom>
</BorderPane>

AddTabsController.java:

import javafx.fxml.FXML;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;

public class AddTabsController  {

    @FXML
    private TabPane tabPane ;

    public void initialize() {
        tabPane.getTabs().add(new Tab("Tab 1"));
    }

    @FXML
    private void addTab() {
        int numTabs = tabPane.getTabs().size();
        Tab tab = new Tab("Tab "+(numTabs+1));
        tabPane.getTabs().add(tab);
    }

    @FXML
    private void listTabs() {
        tabPane.getTabs().forEach(tab -> System.out.println(tab.getText()));
        System.out.println();
    }
}

Application (AddTabsExample.java):

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class AddTabsExample extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        BorderPane root = FXMLLoader.load(getClass().getResource("AddTabsExample.fxml"));
        primaryStage.setScene(new Scene(root, 800, 600));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
Sadequer Rahman

Use this instead. You have to override initialize() method:

@Override
public void initialize(URL location, ResourceBundle resources) {
    tabPane.getTabs().add(new Tab("Tab 1"));
} 

Not this:

public void initialize() {
    tabPane.getTabs().add(new Tab("Tab 1"));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!