jaredvanvels
jaredvanvels

Reputation: 11

How to restrict amount of selected CheckBoxes - JavaFX

Is it possible to allow only 3 CheckBoxes to be checked at a time in JavaFX, exactly like what is on this page: http://jsfiddle.net/sarathsprakash/m5EuS/680/

var theCheckboxes = $(".pricing-levels-3 input[type='checkbox']");
theCheckboxes.click(function()
{
    if (theCheckboxes.filter(":checked").length > 3)
    $(this).removeAttr("checked");
});

but in JavaFX.

I need to have only 3 boxes be select-able at a time out of a group of checkboxes that I have. So I have 10 checkboxes in my program but I need a group of 6 of those to only have 3 checked at a time. How can I go about doing this in JavaFX?

Upvotes: 0

Views: 1770

Answers (1)

Mordechai
Mordechai

Reputation: 16294

Very simple, use change listeners:

CheckBox[] myCheckboxes = ...;
int maxSel = 3;

for (int i = 0 ; i < myCheckboxes.length;i++)
    myCheckboxes[i].selectedProperty().addListener( (o, oldV, newV) -> {
        if(newV) {
            int sel = 0;
            for(CheckBox cb : myCheckboxes)
                if(cb.isSelected())
                    sel++;

            o.set(sel <= maxSel);
        }
    });

Hope this works.

Upvotes: 1

Related Questions