[英]JavaFx: Get the clicked button value
以下代码如何获取按钮的值?
String value = ((Button)event.getSource()).getText();
这是一个可以让它更清晰的片段:
Button button = new Button("Click Me");
button.setOnAction(event -> {
Object node = event.getSource(); //returns the object that generated the event
System.out.println(node instanceof Button); //prints true. demonstrates the source is a Button
//since the returned object is a Button you can cast it to one
Button b = (Button)node;
System.out.println(b.getText());//prints out Click Me
});
上述详细处理程序的实际简写形式可以是:
button.setOnAction(event -> {
System.out.println(((Button)event.getSource()).getText());//prints out Click Me
});
如果处理程序用于特定按钮,则此代码段可能是:
button.setOnAction(event -> {
System.out.println(button.getText());//prints out Click Me
});
我遇到了类似的问题,这有帮助。
private void loadWhenClicked(ActionEvent event){
Button button = (Button) event.getSource();
System.out.println(button.getText()); // prints out button's text
}
正如@Sedrick所提到的,event.getSource返回一个对象。 既然您知道该对象是一个Button对象,那么您将其转换为一个对象。 (如果我没有按照任何规则回答,我很抱歉,因为这是我的第一个回答:D)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.