3

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?

Yuan Vivien Wang
  • 35
  • 1
  • 1
  • 4

1 Answers1

3

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());
}
atilacamurca
  • 168
  • 1
  • 9
  • 12
Aditya Singh
  • 2,343
  • 1
  • 23
  • 42