[英]JavaFx- Clone tab dynamically based on input
這是一個閱讀注釋的示例,如果您想自己保存一行代碼,可以在標簽中添加fxml並將其加載到標簽窗格中
主班
public class Main extends Application {
@Override
public void start(Stage stage) {
TabPane tabPane = new TabPane();
ArrayList<Controller> controllerArrayList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
//Don't just load it into the new node save a reference
FXMLLoader loader = new FXMLLoader(getClass().getResource("/sample.fxml"));
try {
//Load it into the new parent node
Tab tab = new Tab("Tab:"+i, loader.load());
//Save contoller to arraylist of controllers
controllerArrayList.add(loader.getController());
//Add to tabPane
tabPane.getTabs().add(tab);
} catch (IOException e) {
e.printStackTrace();
}
}
//Do some stuff with your contollers
int index = 0;
for (Controller controller : controllerArrayList) {
controller.setLabel("index:"+index);
controller.setTextField("index:"+index++);
}
Scene scene = new Scene(tabPane);
stage = new Stage();
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) { launch(args); }
}
控制器類
public class Controller{
public TextField textField;
public Label label;
public void setTextField(String text){ textField.setText(text); }
public void setLabel(String text){ label.setText(text); }
}
XML文件
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.VBox?>
<VBox alignment="CENTER" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Controller">
<children>
<Label fx:id="label"/>
<TextField fx:id="textField" />
</children>
</VBox>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.