Button ActionEvent获取按钮JavaFX的源代码

Button ActionEvent获取按钮JavaFX的源代码,button,javafx,get,actionevent,Button,Javafx,Get,Actionevent,我有大约10个按钮将被发送到相同的方法。我希望该方法能够识别源代码。因此,该方法知道按钮“完成”已触发此功能。然后我可以添加if语句的switch case来相应地处理它们。这就是我尝试过的 //Call: btnDone.setOnAction(e -> test(e)); public void test(ActionEvent e) { System.out.println("Action 1: " + e.getTarget());

我有大约10个按钮将被发送到相同的方法。我希望该方法能够识别源代码。因此,该方法知道按钮“完成”已触发此功能。然后我可以添加if语句的switch case来相应地处理它们。这就是我尝试过的

//Call:
    btnDone.setOnAction(e -> test(e));


   public void test(ActionEvent e) {
        System.out.println("Action 1: " + e.getTarget());
        System.out.println("Action 2: " + e.getSource());
        System.out.println("Action 3: " + e.getEventType());
        System.out.println("Action 4: " + e.getClass());
    }
输出结果:

Action 1: Button@27099741[styleClass=button]'Done'
Action 2: Button@27099741[styleClass=button]'Done'
Action 3: ACTION
Action 4: class javafx.event.ActionEvent
按钮上的文本已完成。正如您所看到的,我可以使用
e.getTarget()
和/或
e.getSource()
然后我必须对其进行子串,因此只显示“完成”。有没有其他方法可以在撇号中获得字符串,而不必使用子字符串

更新:我已经试过通过按钮,它的工作,但我仍然想 了解使用ActionEvent的解决方案


输出是动作1:完成,通常我更喜欢对每个按钮使用不同的方法。通常,依赖按钮中的文本是一个非常糟糕的主意(例如,如果您想国际化您的应用程序,逻辑会发生什么变化?)

如果您真的想在按钮中获取文本(我必须再次强调,您真的不想这样做),只需使用向下转换:

String text = ((Button)e.getSource()).getText();

正如@James_D所指出的,由于各种原因,依赖于向用户显示的按钮文本是一个坏主意(这对于您的情况来说可能已经足够了!)

另一种方法是,将ID分配给按钮,然后在回调方法中检索它们。看起来是这样的:

// that goes to the place where you create your buttons
buttonDone.setId("done");

...

// that goes inside the callback method
String id = ((Node) event.getSource()).getId()

switch(id) {
    case "done":
        // your code for "buttonDone"
        break;
}

我明白了,所以选角成功了。谢谢,正是我想要的。我总是乐于学习,那么你更喜欢什么来代替这个?@CookieMonster:将数据附加到节点的替代方法:和
// that goes to the place where you create your buttons
buttonDone.setId("done");

...

// that goes inside the callback method
String id = ((Node) event.getSource()).getId()

switch(id) {
    case "done":
        // your code for "buttonDone"
        break;
}