java - 使用 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
.
解决方案
为什么不做
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();
}
推荐阅读
- c++ - 如何在 Qt 上实现 GDAL 库?
- javascript - 为什么移动设备在使用语音合成时对相同的语言使用相同的声音?
- mysql - 迁移失败,出现警告“'utf8' 当前是字符集 UTF8MB3 的别名,但在未来版本中将是 UTF8MB4 的别名”
- python - 如何在自定义图层中重塑 keras 蒙版
- c++ - 如何修复“Vcpkg/CMake 无法确定目标架构”(Windows10、vcpkg、clion、cmake)
- docker - 容器开始运行脚本
- python - 将列表列表转换为字典
- c# - 将值从父 Page ViewModel 绑定到 UserControl
- java - 如何调用 getDialog.dismiss 从另一个类(非嵌套)中的 AsyncTask 类中解除对话框片段?
- cassandra - 生成 keyspace system_schema cassandra