![](/img/trans.png)
[英]How to add 1 to the Text of a Tab in every time on click on a button? in 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;
}
}
如果您希望它像在瀏覽器中一樣,則應使用此代碼。 這在末尾使用了一個空選項卡,它就像一個按鈕。 您可以在選項卡 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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.