How to get a handle to all JCheckBox objects in order to loop?

Posted by EmmyS on Stack Overflow See other posts from Stack Overflow or by EmmyS
Published on 2010-05-22T21:56:54Z Indexed on 2010/05/22 22:00 UTC
Read the original article Hit count: 310

Filed under:
|

I'm very new to Java and am having some issues looping through JCheckBoxes on a UI. The idea is that I have a bunch of checkboxes (not in a group because more than one can be selected.) When I click a JButton, I want to build a string containing the text from each selected checkbox. The issue I'm having is that our instructor told us that the checkboxes need to be created via a method, which means (see code below) that there isn't a discrete instance name for each checkbox. If there were, I could say something like

if(checkBox1.isSelected()) {
  myString.append(checkBox.getText());
}

That would repeat for checkBox2, checkBox3, and so on. But the method provided to us for adding checkboxes to a panel looks like this:

public class CheckBoxPanel extends JPanel {
private static final long serialVersionUID = 1L;

public CheckBoxPanel(String title, String... options) {
    setBorder(BorderFactory.createTitledBorder(BorderFactory
            .createEtchedBorder(), title));
    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

    // make one checkbox for each option
    for (String option : options) {
        JCheckBox b = new JCheckBox(option);
        b.setActionCommand(option);
        add(b);
    }
}

}

This is called like this:

toppingPanel = new CheckBoxPanel("Each Topping $1.50", "Tomato", "Green Pepper", 
                                    "Black Olives", "Mushrooms", "Extra Cheese",
                                    "Pepperoni", "Sausage");

So I now have a panel that contains a border with the title "Each Topping $1.50", and 7 visible checkboxes. What I need to do is get a list of all the selected toppings. We are not supposed to use an ActionListener for each checkbox, but rather get the list when a button is clicked. I'm feeling really clueless here, but I just can't figure out how to get the isSelected property of the checkboxes when the individual checkboxes don't have instance names.

Ideally I'd like to somehow add all the checkboxes to an array and loop through the array in the button's action listener to determine which ones are checked, but if I have to check each one individually I will. I just can't figure out how to refer to an individual checkbox when they've been created dynamically.

© Stack Overflow or respective owner

Related posts about java

Related posts about swing