Skip to content
Advertisement

How to set order for dynamically added JavaFX components?

I have a button that generates another button each time it’s clicked. 1 of the problems is, that the generated button is placed in the wrong location. The buttons should start around the Top Left side of the window, but the location of the buttons is at the bottom left of the window. I can’t use the function setAlignment(Pos.TOP_LEFT) to change the location because the generated buttons are children of an AnchorPane object.

Nor can I use something like Scenebuilder, since the generated buttons only exist after a button has been clicked.

If I set the buttons to be children of a VBox object, and change the parameter in the function `vbox.getChildren().add(0, new Button( ” New Entry “+button1ClickCount )) to a 1 instead of 0, the buttons are created in an ascending order, starting at the top of the window, but all the children below the generated buttons get pushed below the screen + the first generated button doesn’t stay above newer generated buttons.

How do you set the location in Java for a Button or other component that doesn’t exist before runtime? And have them in an ascending order, instead of descending, without pushing out FXML components below the newly generated ones?

The button at the bottom of the window in the image should appear right below and to the left of the blue folder.

wrong location

My Main.Java class

JavaScript

The Button FXML Controller Class

JavaScript

My FXML file

JavaScript

Advertisement

Answer

You can use setLayoutX and setLayoutY in the ButtonFXMLController with a y incremented to ensure that the buttons will not created in the same place:

JavaScript
Advertisement