Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaFx:获取单击的按钮值_Java_Javafx_Javafx 8 - Fatal编程技术网

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文档。当您尝试它时发生了什么…;)@Sedrick
event.getSource()
返回
Object
weeeell。。。你不应该抄袭其他答案——与公认的答案相比,这里没有什么新东西,是吗;)