Java Swing Group of checkbox multiple selection handler

自闭症网瘾萝莉.ら 提交于 2020-01-25 04:21:05

问题


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?


回答1:


No.
Create an array of JCheckBoxes.

For ex:

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


来源:https://stackoverflow.com/questions/26241488/java-swing-group-of-checkbox-multiple-selection-handler

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