我想创建一个按钮,单击时将在 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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)