Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing Group of checkbox multiple selection handler

I have a group of checkboxes (multiple selection) and I want to know which items are selected using ListSelectionListener

    Box box = new Box(BoxLayout.Y_AXIS);
    foodBox = new JCheckBox("");
    proteinBox  = new JCheckBox("");
    noLabelBox =  new JCheckBox("");
    aggregateBox =  new JCheckBox("");

    box.add(getLegendSpecificBox("FOOD", new Color(0, 255, 127), 0));
    box.add(foodBox);
    box.add(getLegendSpecificBox("PROTEIN", new Color(240, 230, 140), 0));
    box.add(proteinBox);
    box.add(getLegendSpecificBox("NO LABEL", new Color(220, 220, 220), 0));
    box.add(noLabelBox);
    box.add(getLegendSpecificBox("AGGREGATION", new Color(255, 140, 0), 0));
    box.add(aggregateBox);

I have a graph with nodes with labels of either food, protein or aggregate. What I want to achieve is when I check food checkbox, I grey out nodes with other label(protein, etc). But I want to allow multiple selection too, for example, when I check food checkbox and protein checkbox, it will grey out other labels(aggregate etc) but food and protein maintain their original color.

I was using ItemListener and add it to every checkbox but it does not work because I can not detect with other checkboxes are also checked.

Can you help me about it? would ListSelectionListener do the trick?

like image 996
Yuan Vivien Wang Avatar asked Jul 28 '26 15:07

Yuan Vivien Wang


1 Answers

No.
Create an array of JCheckBoxes.

For example:

String[] food = {"Pizza", "Burger", "Pasta", "Hot Dog", "etc"};

JCheckBox[] boxes = new JCheckBox[food.length]; //  Each checkbox will get a name of food from food array.  

for(int i = 0; i < boxes.length; i++)
    boxes[i] = new JCheckBox(food[i]);

Now we create a method to check which box is selected. You can probably copy the same method body to an action listener:

public void printSelectedNames(JCheckBox[] boxes) {

    for(JCheckBox box : boxes)
        if(box.isSelected())
            System.out.println(box.getText());
}
like image 94
Aditya Singh Avatar answered Jul 30 '26 05:07

Aditya Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!