javafx - 将所选项目从组合框设置为文本字段
问题描述
我想根据 ComboBox 中的选定项设置 TextField 的文本
解决方案
据我了解您的问题,您希望TextField
根据ComboBox
. 可能您只是在使用您在评论中提到的:personnelcongetxt.setText(String.valueOf(personneList.getValue()));
每次选择不同的项目时都不会更新您的值。它始终为 null,因为默认选择(如果您未设置)为 null,因此它在Textfield
. 如果要更新有两种方法:
- 使用绑定。
- 使用监听器。
这是代码:
public class Controller implements Initializable {
@FXML
private ComboBox<Model> cb;
@FXML
private TextField tf;
@Override
public void initialize(URL location, ResourceBundle resources) {
initCB();
// Solution one : using bindings :
tf.textProperty().bind(Bindings.when(cb.getSelectionModel().selectedItemProperty().isNull())
.then("")
.otherwise(cb.getSelectionModel().selectedItemProperty().asString())); // uses toString of the Model
// Solution two using listener :
// cb.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
// tf.setText(newValue.toString()); // or newValue.getName();
// });
}
private void initCB() {
cb.setItems(FXCollections
.observableArrayList(new Model("Apple"), new Model("Banana"), new Model("")));
}
private class Model {
private String name;
public Model(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return name;
}
}
}
根据您的选择,结果可能会有所不同。
如果您使用的是第一个解决方案(绑定),那么您将无法通过键入文本字段的文本来“手动”更改,但您可以确保
TextField
每次组合框的选定项目都会显示。如果您使用的是第二种解决方案(侦听器),那么 textField 的值会在您选择一个新项目后更新,但之后它可以让您随时编辑文本字段,并且您可以将文本更改为任何字符串。所以如果你想要这个功能,那么你应该这样做。
长话短说:绑定始终显示所选项目,侦听器仅在选择新项目后显示。
推荐阅读
- laravel - 如何在 Laravel 刀片上使用 Vuejs
- python - 匀称并使用形状边界找到重叠
- android - 将元数据添加到上传的图像 Firebase/Kotlin
- c# - 如何制作供全球使用的 DataReader
- excel - 尝试在 Excel 宏中制作图表时出错
- python - 如何在 python 和输出脚本中获取 condor 作业编号?
- visual-studio-code - Visual Studio Code 无法识别 Svelte 中的 SCSS
- raspberry-pi - 从 github 项目运行 shell 文件
- r - 当行是唯一的时,从 R 中的数据框中删除重复值
- node.js - Firebase 不读取随机键