【问题标题】:JavaFX bidirectional binding of choicebox选择框的JavaFX双向绑定
【发布时间】:2015-03-12 12:26:21
【问题描述】:

我的问题很简单,有没有办法在选择框的项目和数组列表之间进行双向绑定(可以从另一个类中添加和删除)

我的 SettingsService 包含一个简单的 ArrayList,其中包含 User 对象。可以从我的应用程序中的其他类和位置添加新项目。 如果我将用户添加到此列表中,新项目如何自动出现在选择框中?

例子:

视图模型

public class ViewModel {
    private SettingsService settings = new SettingsService();
    public final ObjectProperty<ObservableList<User>> userChoiceBoxItems = new SimpleObjectProperty<>();

    public ViewModel() {
        userChoiceBoxItems.setValue(FXCollections.observableArrayList(settings.getUsers()))
    }
}

查看

public class View {

    private ViewModel viewModel = new ViewModel();

    @FXML
    ChoiceBox<User> userChoiceBox;

    @FXML
    public void initialize() {
        userChoiceBox.itemsProperty().bindBidirectional(viewModel.userChoiceBoxItems);
}

感谢您的帮助

【问题讨论】:

  • 如果SettingsService 只是一个普通的List,而不是一个ObservableList,那么当SettingsService 中的列表被修改时,就没有内置的通知方式。如果您能够修改SettingsService,您可以将其更改为使用ObservableList,或触发IndexedPropertyChangedEvents,然后编写代码将这些事件连接到您选择框中的列表。
  • 你是如何创建列表的?
  • @James_D 是的,我是从 FXCollections.emptyObservableList() 创建它的,这是错误的。将其更改为FXCollections.observableArrayList() 如果您将其发布为一个,我将很乐意接受您的回答:) 谢谢!

标签: java javafx javafx-8 bidirectional


【解决方案1】:

创建一个新的ObservableListObservableList&lt;User&gt; tempList = FXCollections.observableArrayList() 并将所有项目添加到列表中 templist.addAll(userChoiceBoxItems) 然后双向绑定

【讨论】:

    猜你喜欢
    • 2021-11-04
    • 2015-03-01
    • 1970-01-01
    • 2015-01-19
    • 2017-04-22
    • 2014-01-09
    • 1970-01-01
    • 2012-03-11
    • 2017-11-07
    相关资源
    最近更新 更多