简体   繁体   中英

JavaFx- Clone tab dynamically based on input

I am parsing an XML file and populating the javafx fields with the XML values. However, these fields are in a tab & I want to clone the tab & its content based on the node count from the XML. Below is the fxml file screenshot:

在此处输入图片说明

I know one method of doing it is have the tab content in a separate FXML file and include it, but the problem of doing so is I have to populate the fields with data & I won't be able to populate data if load same fxml file multiple times with duplicate fx:ids.

Any method by which the above can be achieved?

Here is an example read the comments and you could probably do you fxml in a tab and load it into the tab pane if you want to save yourself a line of code

Main Class

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

Controller Class

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

FXML

<?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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM