如何在JAVAFX中创建一个“添加标签”按钮?

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

我想创建一个按钮,它会在点击时为 tabPane 创建一个新标签,并且始终在所有标签的右侧。如果有任何示例,我将不胜感激。

您的代码应该类似于下面的代码。 此示例使用 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;
    }
}

如果您希望它像在浏览器中一样,这段代码应该可以做到。 这在末尾使用了一个空选项卡,它就像一个按钮。您可以在选项卡标签中添加类似 + 的图标,而不是文本。

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;
    }
}