我想根据组合框中的选定项目设置 TextField 的文本
据我了解您的问题,您想TextField
根据ComboBox
. 可能您只是像评论中提到的那样使用:personnelcongetxt.setText(String.valueOf(personneList.getValue()));
每次选择不同的项目时,它都不会更新您的值。它始终为空,因为默认选择(如果您未设置)为空,因此它在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 的值会更新,但之后它允许您随时编辑文本字段,并且您可以将文本更改为任何字符串。所以如果你想要这个功能,那么你应该走这条路。
长话短说:绑定始终显示所选项目,侦听器仅在选择新项目后显示。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句