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.
JavaFX controller works based on MVC(Model-View-Controller) JavaFX MVC can be achieved by FXML (EFF-ects eXtended Markup Language). FXML is an XML based language used to develop the graphical user interfaces for JavaFX applications as in the HTML.
public class FXMLLoader extends Object. Loads an object hierarchy from an XML document.
FXML is an XML-based language that provides the structure for building a user interface separate from the application logic of your code.
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.
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) {
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With