JavaFx:获取点击的按钮值

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 returns 一个对象。因为您知道该对象是一个 Button 对象,所以您将其转换为一个。 (如果我没有按照任何规则回答,我深表歉意,因为这是我的第一个回答:D)