Put them in a List<JCheckBox>
such as an ArrayList<JCheckBox>
and then iterate through the list to find the ones that are checked.
i.e.,
// assuming a List<CheckBox> called checkBoxList
for (JCheckBox checkBox : checkBoxList) {
if (checkBox.isSelected()) {
String actionCommand = checkBox.getActionCommand();
// do something here for that checkBox
}
}
If on the other hand you need to perform certain actions when a check box has been checked, you could always use a Map<JCheckBox, Runnable>
such as a HashMap, and then run the Runnable if the check box is selected.
Edit
A modification of your code posted in the comment (again, please avoid doing that), works fine for me:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
@SuppressWarnings("serial")
public class CheckBoxFun extends JPanel {
// the list should be a class field, not a local variable
private List<JCheckBox> checkboxes = new ArrayList<JCheckBox>();
public CheckBoxFun() {
JPanel checkBoxPanel = new JPanel();
checkBoxPanel.setLayout(new GridLayout(3, 3));
checkBoxPanel.setBorder(BorderFactory.createTitledBorder("Check boxes"));
JCheckBox checkbox;
String labels[] = { "jCheckBox1", "jCheckBox2", "jCheckBox3",
"jCheckBox4", "jCheckBox5", "jCheckBox6", "jCheckBox7",
"jCheckBox8", "jCheckBox9" };
for (int i = 0; i < labels.length; i++) {
checkbox = new JCheckBox(labels[i]);
checkboxes.add(checkbox);
checkBoxPanel.add(checkbox);
}
JButton checkBoxStatusBtn = new JButton(new CheckBoxStatusAction());
JPanel buttonPanel = new JPanel();
buttonPanel.add(checkBoxStatusBtn);
setLayout(new BorderLayout());
add(checkBoxPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.PAGE_END);
}
private class CheckBoxStatusAction extends AbstractAction {
public CheckBoxStatusAction() {
super("Check CheckBoxes");
putValue(MNEMONIC_KEY, KeyEvent.VK_C);
}
@Override
public void actionPerformed(ActionEvent e) {
for (JCheckBox checkBox : checkboxes) {
if (checkBox.isSelected()) {
System.out.println("Check Box Selected: " + checkBox.getActionCommand());
}
}
}
}
private static void createAndShowGui() {
CheckBoxFun mainPanel = new CheckBoxFun();
JFrame frame = new JFrame("CheckBoxFun");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}