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

复选框(ControlsFX)设置为只读[JavaFX]

  •  2
  • EDJ  · 技术社区  · 7 年前

    我一直在想如何设置 CheckComboBox 只读。

    我不想禁用 复选框组合框 因为我希望用户能够滚动并查看已选中的项目,但是我不允许选中/取消选中项目。

    有没有办法做到这一点?

    1 回复  |  直到 7 年前
        1
  •  2
  •   DVarga    7 年前

    粗糙易碎,但有效:

    public class CheckComboReadOnlySkin<T> extends CheckComboBoxSkin<T> {
        public CheckComboReadOnlySkin(CheckComboBox control) {
            super(control);
    
            ((ComboBox) getChildren().get(0)).setCellFactory((Callback<ListView<T>, ListCell<T>>) listView -> {
                CheckBoxListCell<T> result = new CheckBoxListCell<>(item -> control.getItemBooleanProperty(item));
                result.getStyleClass().add("readonly-checkbox-list-cell");
                result.setDisable(true);
                result.converterProperty().bind(control.converterProperty());
                return result;
            });
        }
    }
    

    虽然

    checkComboBox.setSkin(new CheckComboReadOnlySkin<String>(checkComboBox));
    

    完全使用:

    final ObservableList<String> strings = FXCollections.observableArrayList();
    for (int i = 0; i <= 50; i++) 
        strings.add("Item " + i);
    
    // Create the CheckComboBox with the data
    final CheckComboBox<String> checkComboBox = new CheckComboBox<>(strings);
    for (int i = 0; i< checkComboBox.getCheckModel().getItemCount(); i++) {
        if (i % 3 == 0)
            checkComboBox.getCheckModel().check(i);
    }
    checkComboBox.setSkin(new CheckComboReadOnlySkin<String>(checkComboBox));
    checkComboBox.getStylesheets().add(getClass().getResource("app.css").toString());
    

    在应用程序中。css:

    .readonly-checkbox-list-cell{-fx-opacity : 1;}
    .readonly-checkbox-list-cell .check-box{-fx-opacity : 1;}
    

    结果: enter image description here

    我希望有人能想出一个更好的。