glasspill
glasspill

Reputation: 1300

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,

Upvotes: 7

Views: 9065

Answers (1)

HMarioD
HMarioD

Reputation: 842

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
        }
    }
}

Upvotes: 11

Related Questions