JavaFX2 FXML how to add elements (e.g. Buttons) dynamically

user1562969 picture user1562969 · Jul 30, 2012 · Viewed 17.2k times · Source

So, what I want to do is, creating a custom element by using fxml and then add a couple of instances of that element into a container, like GridPane. The "new" operators does not work for me, because I would like to use the @fxml annotator to get access to the element. Cloning would be nice, but it does not work. The FXMLLoader is very slow, when using in a for() contruct to add many elements. It would be perfect, if I could write a reference into fxml parentnode, which could be called from the controller.

Sorry... here in pseudo...

public class Controller implements Initializable {

    @FXML
    private VBox stack;

    @FXML
    private Button button;

    @FXML
    private void Change(KeyEvent event) throws IOException {     
        for (int i=0; i<10; i++){
            stack.getChildren().add(button);   
        }
    }

}

It is no problem to add THE button to the VBox. But in a for-contruct (to add MORE THAN ONE Button) it fails. I could use the new operator in the for construct, but I want to know, if this is the only possiblity. I thought there must be another way e.g. to use the @FXML annotator to "get" the button and then duplicate it.

Answer

Yarrgh picture Yarrgh · Jul 30, 2012

I believe it fails because you are trying to add the same button over and over. In the for loop you need to create an instance of a button every time the code in the loop gets ran.

Something like:

@FXML
private void Change(KeyEvent event) throws IOException {     
    for (int i=0; i<10; i++){
        stack.getChildren().add(new Button("test")) ;   
    }   
}

Let me know if i have misunderstood you.