How can I remove a certain JCheckBox if it is selected?

I am using an Arraylist for my Checkboxes. I want to remove each one once it is selected but my code isn't carrying out the expected behaviour. I don't know why my code isn't working.

Here it is:

public class sampledsa extends JFrame implements ActionListener {

    private JCheckBox CBname;
    private ArrayList < JCheckBox > SBname = new ArrayList < > ();
    private JButton BTok;

    public sampledsa() {
        setVisible(true);
        setSize(500, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridLayout(6, 1));

        BTok = new JButton("OK");

        for (int i = 0; i < 5; i++) {
            CBname = new JCheckBox("Checkbox" + (i + 1));
            SBname.add(CBname);
            add(SBname.get(i));
        }

        add(BTok);
        BTok.addActionListener(this);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource().equals(BTok)) {
            for (int i = 0; i < SBname.size(); i++) {
                if (SBname.get(i).isSelected()) {
                    SBname.remove(i);
                }
            }
            JFrame f = new JFrame();
            f.setVisible(true);
            f.setSize(500, 400);
            f.setDefaultCloseOperation(EXIT_ON_CLOSE);
            for (int i = 0; i < SBname.size(); i++) {
                f.add(SBname.get(i));
            }
        }
    }

    public static void main(String[] args) {
        new sampledsa();
    }

}

Upvotes: 0

Views: 308

Answers (2)

mayha
mayha

Reputation: 603

As others pointed out in the comment section you should not remove items of an ArrayList because you won't get the expected result.

You should use an Iterator instead.

Example:

Iterator<JCheckBox> iterator = sbname.iterator(); 
while(iterator.hasNext()) {
   JCheckBox checkbox = iterator.next();
   if (checkbox.isSelected()) {
      iterator.remove();
      //do some more stuff
   }
}

Upvotes: 2

matt
matt

Reputation: 12346

Use the modern Collection API.

SBName.removeIf(box->box.isSelected());

Or use a method reference.

SBName.removeIf(JCheckBox::isSelected);

Upvotes: 0

Related Questions