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

巧了我就是萌 提交于 2019-12-22 05:07:38

问题


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:


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


来源:https://stackoverflow.com/questions/14085076/javafx-pass-fxid-to-controller-or-parameter-in-fxml-onaction-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!