【问题标题】:JavaFX 8: ComboBox button cell update behaviorJavaFX 8:组合框按钮单元格更新行为
【发布时间】:2015-08-18 07:24:35
【问题描述】:

我有一个组合框,其中包含Dog 类型的项目。如果所有项目都替换为新项目(通过ObservableList 模型上的setAll),项目渲染器可以应对此更新,而按钮单元格渲染器则不能:

这是重现问题的最小示例 (full source incl. imports on GitHub):

public class ComboBoxRefresh extends Application {

    private static final class Dog {

        private final String name;

        public Dog(String name) {
            this.name = name;
        }
    }

    private static final class DogListCell extends ListCell<Dog> {
        @Override
        public void updateItem(Dog item, boolean empty) {
            super.updateItem(item, empty);
            if (item == null || empty) {
                setText("");
            } else {
                setText(item.name);
            }
        }
    }

    private static List<Dog> createThreeDogs() {
        return range(0, 3).mapToObj(i -> new Dog("Buddy " + i)).collect(toList());
    }

    @Override
    public void start(Stage stage) throws Exception {
        ObservableList<Dog> items = observableArrayList(createThreeDogs());
        ComboBox<Dog> comboBox = new ComboBox<>(items);
        comboBox.setPrefWidth(400);
        comboBox.setCellFactory(listView -> new DogListCell());
        comboBox.setButtonCell(new DogListCell());

        Button button = new Button("Refresh");
        button.setOnAction(event -> {
            List<Dog> newItems = createThreeDogs();
            items.setAll(newItems);
        });

        VBox box = new VBox(10, comboBox, button);
        box.setPadding(new Insets(10));

        Scene scene = new Scene(box);
        stage.setScene(scene);
        stage.show();
    }

}

如果我将 equals 实现添加到 Dog 类,一切正常,但在我的实际应用程序中这不是一个选项。

是否有任何变通方法来强制正确刷新按钮单元格?

【问题讨论】:

  • 我看到了类似的东西。似乎当项目列表中不存在所选值时,所选值是使用 .toString 而不是按钮单元格呈现的。你提交错误报告了吗?

标签: combobox javafx-8


【解决方案1】:

这似乎是一个错误。解决方法可能是

button.setOnAction( event -> {
    List<Dog> newItems = createThreeDogs();
    items.clear();
    items.addAll(newItems);
} );

【讨论】:

  • Tx 为您解答。您的解决方法会丢失选择,因此按钮单元格渲染器不会出现异常行为,因为它不再有任何要渲染的内容:) 但是,您的回答启发了我务实地重新应用基于索引的选择,它也可以与 setAll 结合使用。 ..
  • @netzwerg 很高兴听到这个消息。您可以发布答案。
  • @netzwerg 您希望选择是什么?如果要替换组合框中的所有元素,并且不覆盖 equals,那么所选元素是否不再在组合框的列表中?在这种情况下,选择为空是否有意义?
  • @James_D 你是完全正确的,没有正确的方法可以覆盖equals。恕我直言,我原始示例背后的真正错误是选择没有丢失的事实。选择模型(以及按钮单元格)指向不再是模型一部分的旧 Dog 实例(类似于手动调用 comboBox.getSelectionModel().select(new Dog("Not In Model"))
猜你喜欢
  • 1970-01-01
  • 2014-11-26
  • 2015-11-28
  • 1970-01-01
  • 2017-11-19
  • 1970-01-01
  • 2018-11-22
  • 2016-05-09
  • 1970-01-01
相关资源
最近更新 更多