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.
Asked
Active
Viewed 1,284 times
4
-
assuming you want the "+" as f.i. in firefox tabs: not supported directly, you might try to either write your own TabPaneSkin or search for a 3rd party that supports it. Or hack around, add a tab with the plus as title and on selecting it the first time, fill its content and add another with the plus. – kleopatra Jun 01 '20 at 11:22
1 Answers
2
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;
}
}

Noah
- 102
- 1
- 7
-
1hmm .. I suspect that's not what the OP wants - the requirement seems to be more like the "+" in f.i. firefox tabs .. – kleopatra Jun 01 '20 at 11:21
-