CheckComboBox(ControlsFX) set to read only [JavaFX]

北战南征 提交于 2021-02-10 07:27:09

问题


I have been trying to figure out how to set CheckComboBox to read-only.

I do not want to disable the CheckComboBox because I want the user to be able to scroll and look through the already checked items, however I want to disallow the ability of checking/unchecking an item.

Is there a way to do this?


回答1:


Hacky and fragile, but works:

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

while

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

Full usage:

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());

while in app.css:

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

Result:

I hope someone will come up with a better one.



来源:https://stackoverflow.com/questions/47810781/checkcomboboxcontrolsfx-set-to-read-only-javafx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!