java - 自定义检查组合框

标签 java javafx controlsfx

我正在使用 ControlsFX 中的 CheckComboBox 控件项目。

但我想创建一个自定义规则:

当您单击 Item0 时,它应该清除所有其他选择。 如果再次单击 Item0,它将保持选中状态。 如果您选择 Item(X),它将清除 Item0 并选择 Item(X)。

这个想法是 Item0 应该是“All”选项。

enter image description here

编辑:此解决方案适用于 ControlsFX。

最佳答案

我对 ControlsFX 不太熟悉,但稍微搞了一下,我想我找到了解决您问题的方法。下面是一个完整的例子。我希望评论能解决任何问题。

import org.controlsfx.control.CheckComboBox;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

    public void start(Stage mainStage) throws Exception {


        ObservableList<String> items = FXCollections.observableArrayList();

        items.addAll(new String[] { "All", "Item 1", "Item 2", "Item 3", "Item 4" });

        CheckComboBox<String> controll = new CheckComboBox<String>(items);

        controll.getCheckModel().getCheckedItems().addListener(new ListChangeListener<String>() {
            public void onChanged(ListChangeListener.Change<? extends String> c) {

                while (c.next()) {
                    if (c.wasAdded()) {
                        if (c.toString().contains("All")) {

                            // if we call the getCheckModel().clearChecks() this will
                            // cause to "remove" the 'All' too at least inside the model.
                            // So we need to manually clear everything else
                            for (int i = 1; i < items.size(); i++) {
                                controll.getCheckModel().clearCheck(i);
                            }

                        } else {
                            // check if the "All" option is selected and if so remove it
                            if (controll.getCheckModel().isChecked(0)) {
                                controll.getCheckModel().clearCheck(0);
                            }

                        }
                    }
                }
            }
        });

        Scene scene = new Scene(controll);
        mainStage.setScene(scene);
        mainStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

关于java - 自定义检查组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46960776/

相关文章:

javafx-8 - ControlsFX 字体 Awesome 不显示图标

java - 如何将两个 Java 序列化对象链接在一起?

java - 一对多关系中的父实体更新不会删除 Spring Jpa Childs

java - 为给定的模数和指数生成 RSA key

java - Eclipse 文件夹上的圆形取消符号是什么意思?

java - javafx中如何不允许窗口改变大小

java - Controlsfx - 评级宽度

java - 如何使布局的内容可调整大小?

尝试从数据库中删除行时发生 JavaFX 错误

javafx - 如何单独引用 RangeSlider 的每个拇指 (ControlsFX)