首页 > 解决方案 > 使用 onAction 属性返回按钮文本

问题描述

我有一个方法可以接收名称列表,然后为列表中的每个名称创建按钮。我想以字符串的形式返回名称或单击列表中的哪个数字,但我发现很难做到

public static String display(List<String> names) {
    Stage window = new Stage();
    window.setTitle("title");
    GridPane layout = new GridPane();

    for (int i = 0; i < names.size(); i++) {
        Button b = new Button(names.get(i);
        GridPane.setConstraints(b, 0, i);
        b.setOnAction(e - > {
            // return names.get(i);
            // or the number in the list
            // or the text of the button
        });

        layout.getChildren().add(b);
    }

    Scene scene = new Scene(layout, 300, 250);
    window.setScene(scene);
    window.showAndWait();

    return null;
}

我尝试了什么:

    String s = "";
    b.setOnAction(e - > {
        s = b.getText();
    });
    
    return s;

但我收到以下错误:local variable is defined in an enclosing scope must be final or effective final.

标签: javajavafx

解决方案


为什么不做

public static String display(List<String> names) {

  StringBuilder result = new StringBuilder();

  Stage window = new Stage();
  window.setTitle("title");
  GridPane layout = new GridPane();

  for (int i = 0; i < names.size(); i++) {
    String name = names.get(i);
    Button b = new Button(name); GridPane.setConstraints(b, 0, i);
    b.setOnAction(e -> {
        result.append(name);
        window.close();
    });
    layout.getChildren().add(b);
  }

  Scene scene = new Scene(layout, 300, 250);
  window.setScene(scene);
  window.showAndWait();

  return result.toString();

}

如果使用VBox看起来更自然的 a ,则可以使代码更简洁(因为您不需要列表索引):

public static String display(List<String> names) {

  StringBuilder result = new StringBuilder();

  Stage window = new Stage();
  window.setTitle("title");
  VBox layout = new VBox();

  for (String name : names) {
    Button b = new Button(name); 
    b.setOnAction(e -> {
        result.append(name);
        window.close();
    });
    layout.getChildren().add(b);
  }
  Scene scene = new Scene(layout, 300, 250);
  window.setScene(scene);
  window.showAndWait();

  return result.toString();    
}

推荐阅读