Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a “add tab“button in JAVAFX?

I want to create a button ,which will create a new tab to tabPane when clicking,and on the right of all tab alltime. I'll appreciate if there has any example how to do it.

like image 598
indexalice Avatar asked Sep 16 '25 23:09

indexalice


1 Answers

Your code should look similar to the code below. This example uses a button above the TabPane.

public class TabPaneSample extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        TabPane tabPane = new TabPane();

        VBox layout = new VBox(10); // VBox with spacing of 10. Button sits above TabPane
        layout.getChildren().addAll(newTabButton(tabPane), tabPane); // Adding button and TabPane to VBox

        stage.setScene(new Scene(layout));
        stage.show();
    }

    // Button that adds a new tab and selects it
    private Button newTabButton(TabPane tabPane) {
        Button addTab = new Button("Create Tab");
        addTab.setOnAction(event -> {
            tabPane.getTabs().add(new Tab("New Tab")); // Adding new tab at the end, so behind all the other tabs
            tabPane.getSelectionModel().selectLast(); // Selecting the last tab, which is the newly created one
        });
        return addTab;
    }
}

If you want it to be like in a browser, this code should do it. This uses the an empty tab at the end, which acts like a button. You can add an icon like + instead of the text in the tab label.

public class TabPaneSample extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        TabPane tabPane = new TabPane();

        tabPane.getTabs().add(newTabButton(tabPane));

        stage.setScene(new Scene(tabPane));
        stage.show();
    }

    // Tab that acts as a button and adds a new tab and selects it
    private Tab newTabButton(TabPane tabPane) {
        Tab addTab = new Tab("Create Tab"); // You can replace the text with an icon
        addTab.setClosable(false);
        tabPane.getSelectionModel().selectedItemProperty().addListener((observable, oldTab, newTab) -> {
            if(newTab == addTab) {
                tabPane.getTabs().add(tabPane.getTabs().size() - 1, new Tab("New Tab")); // Adding new tab before the "button" tab
                tabPane.getSelectionModel().select(tabPane.getTabs().size() - 2); // Selecting the tab before the button, which is the newly created one
            }
        });
        return addTab;
    }
}
like image 101
Noah Avatar answered Sep 19 '25 19:09

Noah