Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

If you want to access the button, just create the class variable for it.

private Button okButton = null;
private Button cancelButton = null;

In the initialize() method, init the Button and add to the container.

okButton = new Button("OK");
cancelButton = new Button("Cancel");
stack.getChildren().addAll(okButton, cancelButton) ;

Then you can handle button action event:

cancelButton.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent arg0) {
            try {                    
               //close screen
               ((Button)arg0.getSource()).getScene().getWindow().hide();
            } catch (Exception e) {

            }
        }
    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top