我有大约 10 个按钮将发送到相同的方法。我希望该方法能够识别来源。因此,该方法知道按钮"完成"已唤起此函数。然后我可以添加一个 if 语句的开关大小写来相应地处理它们。这是我尝试过的
//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了解解决方案。
//Call:
btnDone.setOnAction(e -> test(btnDone));
public void test(Button e) {
System.out.println("Action 1: " + e.getText());
}
输出Action 1: Done
我更喜欢为每个按钮使用不同的方法。依赖按钮中的文本通常是一个非常糟糕的主意(例如,如果要国际化应用程序,逻辑会发生什么情况?
如果你真的想在按钮中获取文本(再次强调,你真的不想这样做),只需使用向下的:
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;
}