Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javafx pass fx:id to controller or parameter in fxml onAction method

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,

like image 819
glasspill Avatar asked Dec 29 '12 19:12

glasspill


People also ask

How do I specify a controller in fxml?

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.

What is FX ID in fxml?

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.

How do I add fxml to another fxml?

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.

What is the purpose of the attribute FX controller?

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.


1 Answers

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
        }
    }
}
like image 119
HMarioD Avatar answered Oct 24 '22 00:10

HMarioD