代码之家  ›  专栏  ›  技术社区  ›  Marckaraujo

自定义复选框

  •  1
  • Marckaraujo  · 技术社区  · 9 年前

    我正在使用来自的复选框控件 ControlsFX 项目

    当您单击项目0时,它应该清除所有其他选择。 如果选择项(X),则会清除项0并选择项(X)。

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

    enter image description here

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

    1 回复  |  直到 8 年前
        1
  •  1
  •   JKostikiadis    9 年前

    我对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);
        }
    }