开发者

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

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.


I'm assuming you're not allowed to alter the CheckBoxPanel code at all. Which seems like a useless exercise, because in the real world, you'd think that if CheckBoxPanel where a class being provided to you (e.g. in a library) it would include a way of getting the selected options. Anyway, due to the limitation, you could do something like this:

for( int i=0; i<checkBoxPanel.getComponentCount(); i++ ) {
  JCheckBox checkBox = (JCheckBox)checkBoxPanel.getComponent( i );
  if( checkBox.isSelected() ) {
     String option = checkBox.getText();
     // append text, etc
  }
}


I suggest you maintain a list of checkboxes:

List<JCheckBox> checkboxes = new ArrayList<JCheckBox>();

and before add(b) do:

checkboxes.add(b);

You may then iterate through the list of checkboxes in the buttons action-code using a "for-each" loop construct:

for (JCheckBox cb : checkboxes)
    if (cb.isSelected())
        process(cb.getText()); // or whatever.

Alternatively, if you need to keep track of the specific index:

for (int i = 0; i < checkboxes.size(); i++)
    if (checkboxes.get(i).isSelected())
        ....


I would suggest that you dont put each of the checkboxes in a List when you create them. Instead, in your shared ActionListener, you maintain a Set of all selected checkboxes. Use the getSource method on the ActionEvent to identify which checkbox the user selected and then cast it to a JCheckBox. If isSelected() returns true for the item in question, attempt to add it to your selectedItems Set. If it is not, then attempt to remove it.

You can then just iterate over the subset of all items (only those that are selected) and print them to the console.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜