JavaFx:获取单击的按钮值
下面的代码如何获取按钮的值JavaFx:获取单击的按钮值,java,javafx,javafx-8,Java,Javafx,Javafx 8,下面的代码如何获取按钮的值 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 ev
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返回一个对象。既然你知道这个对象是一个按钮对象,你就把它转换成一个按钮对象。
(如果我没有按照任何规则回答,我深表歉意,因为这是我的第一个答案:D)我假定此代码来自事件处理程序?
event.getSource()
返回触发事件的节点。在这种情况下,它是一个按钮
<代码>按钮有一个getText()
方法。去查看Java文档。当您尝试它时发生了什么…;)@Sedrickevent.getSource()
返回Object
weeeell。。。你不应该抄袭其他答案——与公认的答案相比,这里没有什么新东西,是吗;)