首页 > 解决方案 > 将所选项目从组合框设置为文本字段

问题描述

我想根据 ComboBox 中的选定项设置 TextField 的文本

标签: javafx

解决方案


据我了解您的问题,您希望TextField根据ComboBox. 可能您只是在使用您在评论中提到的:personnelcongetxt.setText(String.valueOf(personneList.getValue()));每次选择不同的项目时都不会更新您的值。它始终为 null,因为默认选择(如果您未设置)为 null,因此它在Textfield. 如果要更新有两种方法:

  1. 使用绑定。
  2. 使用监听器。

这是代码:

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 的值会在您选择一个新项目后更新,但之后它可以让您随时编辑文本字段,并且您可以将文本更改为任何字符串。所以如果你想要这个功能,那么你应该这样做。

长话短说:绑定始终显示所选项目,侦听器仅在选择新项目后显示。


推荐阅读