Binding – JavaFX passes FX: ID to the controller or parameter in the fxml onAction method
•
Java
Is there a way to pass parameters to the onAction method in the fxml file? Or can I get the FX: ID of the component that calls the onAction method in some way?
I have several buttons that should do the same thing, such as five buttons with IDS button1 – button 5. When pressed, the corresponding numbers 1-5 should be printed I don't want five onAction methods that are the same as this variable
Any help, appreciation,
Solution
Call only one handler, ActionEvent Source is the object that initiates 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 } } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码