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


Question

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,

1
7
12/29/2012 7:17:17 PM

Accepted Answer

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
        }
    }
}
11
1/15/2013 12:53:41 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon