简体   繁体   中英

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();
    }

}

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
   }
}

Use the modern Collection API.

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

Or use a method reference.

SBName.removeIf(JCheckBox::isSelected);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM