限制复选框已选中。 JavaFX

时间:2018-07-28 06:14:03

标签: javafx checkbox

如何限制用户可以选择的复选框数量?我想这样做,以便用户只能选择3。我想我应该使用isSelected,但是我不知道如何链接所有复选框。

    CheckBox cb1 = new CheckBox("Pepperoni");
    CheckBox cb2 = new CheckBox("Cheese");
    CheckBox cb3 = new CheckBox("Tomato");
    CheckBox cb4 = new CheckBox("Olives");
    CheckBox cb5 = new CheckBox("Chicken");
    //if 3 are already selected, it should not be possible for the user to select more

1 个答案:

答案 0 :(得分:2)

使用合适的数据结构简单地跟踪选定的CheckBoxLinkedHashSet将允许您使用Set功能并确定所插入的第一个)。
可以从侦听器到selected es的CheckBox属性来更新数据结构。

@Override
public void start(Stage primaryStage) throws Exception {
    String[] ingredients = new String[]{
        "Pepperoni",
        "Cheese",
        "Tomato",
        "Olives",
        "Chicken"
    };
    final int maxCount = 3;
    final Set<CheckBox> activeBoxes = new LinkedHashSet<>();

    ChangeListener<Boolean> listener = (o, oldValue, newValue) -> {
        // get checkbox containing property
        CheckBox cb = (CheckBox) ((ReadOnlyProperty) o).getBean();

        if (newValue) {
            activeBoxes.add(cb);
            if (activeBoxes.size() > maxCount) {
                // get first checkbox to be activated
                cb = activeBoxes.iterator().next();

                // unselect; change listener will remove
                cb.setSelected(false);
            }
        } else {
            activeBoxes.remove(cb);
        }
    };

    VBox root = new VBox();

    // create checkboxes
    for (int i = 0; i < ingredients.length; i++) {
        CheckBox cb = new CheckBox(ingredients[i]);
        cb.selectedProperty().addListener(listener);
        root.getChildren().add(cb);
    }

    Scene scene = new Scene(root);
    primaryStage.setScene(scene);
    primaryStage.show();
}

注意::如果您希望用户在选择了3个CheckBox时根本无法选择更多CheckBox,那么当您达到3个时只需禁用所有未选择的CheckBox es选择了final CheckBox[] checkBoxes = new CheckBox[ingredients.length]; ChangeListener<Boolean> listener = new ChangeListener<Boolean>() { private int activeCount = 0; public void changed(ObservableValue<? extends Boolean> o, Boolean oldValue, Boolean newValue) { if (newValue) { activeCount++; if (activeCount == maxCount) { // disable unselected CheckBoxes for (CheckBox cb : checkBoxes) { if (!cb.isSelected()) { cb.setDisable(true); } } } } else { if (activeCount == maxCount) { // reenable CheckBoxes for (CheckBox cb : checkBoxes) { cb.setDisable(false); } } activeCount--; } } }; VBox root = new VBox(); // create checkboxes for (int i = 0; i < ingredients.length; i++) { CheckBox cb = new CheckBox(ingredients[i]); cb.selectedProperty().addListener(listener); root.getChildren().add(cb); checkBoxes[i] = cb; } 项:

<div data-vc-full-width="true" data-vc-full-width-init="true" data-vc-stretch-content="true" class="vc_row wpb_row vc_row-has-fill" style="position: relative; left: -75px; box-sizing: border-box; width: 1366px;">