JavaFX的通外汇:id来控制器或参数FXML的OnAction方法 [英] javafx pass fx:id to controller or parameter in fxml onAction method
问题描述
有没有办法将参数传递给在FXML文件的OnAction方法呢?或者,我可以以某种方式获取外汇:?调用该方法的OnAction组件的ID
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?
我会有几个按钮,应该做同样的事情,说的5个按钮与IDS Button1的 - button5,当pressed,应打印相应的号码1-5。我不希望有5的OnAction方法是相同高达此变量
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.
任何帮助AP preciated,
Any help appreciated,
推荐答案
呼叫只是一个处理程序,该actionEvent.source是发起事件的对象。
Call just one handler, the actionEvent.source is the object that originated the event.
试试这个:
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
}
}
}
这篇关于JavaFX的通外汇:id来控制器或参数FXML的OnAction方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!