How to count the number of JCheckboxes checks?
I have 11 different checkboxes in my JFrame and you want to get the number when each is checked, how much is checked in total. I know how to set up the ItemListener and see if it's checked, but I'm not sure how I can check all of them.
EDIT:
cblist is an ArrayList containing 11 JCheckBoxes. I gave each JCheckBox an item listener, and here is this class that is used when these checkboxes are clicked ...
private class CheckClass implements ItemListener{
public void itemStateChanged(ItemEvent event){
for(cblist.isChecked){
ingnum++;
}
}
}
In the for loop, how can I check all the elements of the ArrayList ... I understand that my syntax is not right now.
source to share
One way is to put all JCheckBoxes in an array or ArrayList<JCheckBox>
, and if desired, just go to the list to see which checkboxes are checked.
Another possible solution: if you have a table structure, use a JTable that contains Booleans in your model, and then optionally iterate over the rows of the TableModel to see which rows contain Boolean.TRUE values.
source to share
My suggestion (perhaps not the best) is to keep all checked CheckBoxes in a list.
So, the listener for all JCheckBoxex will be something like this:
void stateChanged(ChangeEvent e){
if( CheckBox is checked){
// add the checkbox in the list.
} else {
// remove CheckBox in the list.
}
}
To find out how many checkboxes are installed, just count the size of the list.
Sincerely.
you can save a global counter countChecked
and make a frameimplements ItemListener
for everyone JCheckBox
in your frame chkBox.addItemListener(this)
and handle events
public class MyFrame extends JFrame implements ItemListener{
private int countChecked = 0;
private JPanel contentPane;
public MyFrame() {
contentPane = new JPanel();
setContentPane(contentPane);
JCheckBox chckbx = new JCheckBox("New check box");
contentPane.add(chckbx, BorderLayout.CENTER);
chckbx.addItemListener(this);
}
@Override
public void itemStateChanged(ItemEvent ie) {
if(ie.getSource().getClass() == JCheckBox.class)
{
if(ie.getStateChange() == ie.SELECTED)
countChecked++;
else if(ie.getStateChange() == ie.DESELECTED)
countChecked--;
}
}
}
source to share
add an ActionPerformed event listener for all your checkboxes and call this method inside the event handler method to get the number of checkboxes checked:
int countCheckedCheckBoxes(){
Component[] cs = getRootPane().getComponents();
int checkNums = 0;
for(Component c : cs){
if(c instanceof JCheckBox){
if(((JCheckBox)c).isSelected()){
checkNums++;
}
}
}
return checkNums;
}
getRootPane should return the main panel whose components are located on it.
source to share