有没有办法将参数传递给fxml文件中的onAction方法?或者,我可以以某种方式获取调用onAction方法的组件的fx:id吗?
我有几个按钮应该做同样的事情,比如5个带有ids button1的按钮 – 按钮5,当按下时,应该打印相应的数字1-5.我不希望有5个与此变量相同的onAction方法.
任何帮助,赞赏,
解决方法
只调用一个处理程序,actionEvent.source是发起事件的对象.
试试这个:
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 } } }
要么:
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 } } }