Is there any way to pass parameters to the onAction methods in the fxml files? Alternatively, can I somehow get the fx:id of the component that called the onAction method?
I have several Buttons that should do the same thing, say 5 buttons with ids button1 - button5 that, when pressed, should print the corresponding number 1-5. I don't want to have 5 onAction methods that are identical up to this variable.
Any help appreciated,
There are two ways to set a controller for an FXML file. The first way to set a controller is to specify it inside the FXML file. The second way is to set an instance of the controller class on the FXMLLoader instance used to load the FXML document.
The fx:id is the identity associated to component in fxml to build a controller, and the id is used for css. Follow this answer to receive notifications.
The <fx:include> tag can be used to include one fxml file into another. The controller of the included fxml can be injected into the controller of the including file just as any other object created by the FXMLLoader . This is done by adding the fx:id attribute to the <fx:include> element.
As discussed earlier, the fx:controller attribute allows a caller to associate a "controller" class with an FXML document. A controller is a compiled class that implements the "code behind" the object hierarchy defined by the document.
Call just one handler, the actionEvent.source is the object that originated the event.
Try this:
myButton1.setOnAction(new MyButtonHandler());
myButton2.setOnAction(new MyButtonHandler());
private class MyButtonHandler implements EventHandler<ActionEvent>{
@Override
public void handle(ActionEvent evt) {
if (evt.getSource().equals(myButton1)) {
//do something
} else if (evt.getSource().equals(myButton2)) {
//do something
}
}
}
Or:
myButton1.addEventHandler(ActionEvent.ACTION, new MyButtonHandler());
myButton2.addEventHandler(MouseEvent.CLICKED, new MyButtonHandler());
private class MyButtonHandler implements EventHandler<Event>{
@Override
public void handle(Event evt) {
if (evt.getSource().equals(myButton1)) {
//do something
} else if (evt.getSource().equals(myButton2)) {
//do something
}
}
}
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