Search code examples
javajavafxfxml

Create multiple exact FXML objects in JavaFX


I want to create multiple fxml objects inside the window, using code in fxml once. But they are not appearing more than once. Here is my controller code:

public class HelloController {
    @FXML
    private AnchorPane plot = new AnchorPane();

    @FXML
    void AddPlotBlock(ActionEvent event) {
        this.plot.setMinHeight(110.0D);
        this.plot.setMinWidth(250.0D);
        this.plot.setStyle("-fx-background-color: grey");
    }

And FXML:

<AnchorPane maxHeight="-1.0" maxWidth="-1.0" prefHeight="-1.0" prefWidth="-1.0" VBox.vgrow="ALWAYS" style="-fx-background-color: #301934;">
        <children>
            <AnchorPane fx:id="plot"/>
        </children>
</AnchorPane>

Solution

  • Okay, I found how to fix it. To make this you need to change id in FXML main file not in children but in pane (my AnchorPane) and then make AnchorPane with exact name in controller. Then you can initialyze your blocks or anything inside controller and add it in pane. Here is my solution.

    controller >

    plots.getChildren().add(card); // plots is id
    

    upper command is inside button click.

    @FXML
    private AnchorPane plot = new AnchorPane();
    
    @FXML
    public AnchorPane plots;
    

    plot is objects. You can place infinite objects (if you have memory)

    plots is id of anchorpane.

    FXML anchorpane

    <AnchorPane fx:id="plots" maxHeight="-1.0" maxWidth="-1.0" prefHeight="-1.0" prefWidth="-1.0" VBox.vgrow="ALWAYS" style="-fx-background-color: #301934;" />
    

    So anchorpane have id and you add child arguments (plot) to main pane (plots). Thanks for commenting, and rules.