user2935569
user2935569

Reputation: 347

JCheckbox not removing correctly

I asked a question this morning about JCheckbox but was told to narrow down the problem. After several debugging, I kind of narrowed down to the problem but still was not able to solve.

It seems that if I select a JCheckbox and another JCheckbox that is not the subsequent one, both will be removed. (E.g if I select JCheckbox at position 0 and 2 or 3, both will be removed).

But if I select a JCheckbox and then select the subsequent one, it will only delete the first JCheckbox.(E.g if I select JCheckbox at position 0 and 1, only JCheckbox at position 0 will be removed).

How can I resolve this issue?

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class CheckBoxTest extends JPanel {

    JButton deleteBtn = new JButton("Delete!");
    List<JCheckBox> checkboxes = new ArrayList<JCheckBox>();

    public CheckBoxTest() {
        setLayout(new GridLayout(0, 1));
        for(int i = 0; i < 4; i++) {
            checkboxes.add(new JCheckBox());
            checkboxes.get(i).setText("text" + i);
            add(checkboxes.get(i));
        }
        add(deleteBtn);
        deleteBtn.addActionListener(new DeleteBtnActionPerformed());
    }

    public class DeleteBtnActionPerformed implements ActionListener {   

        @Override
        public void actionPerformed(ActionEvent e) {
            for(int i = 0; i < checkboxes.size(); i++) {
                if(checkboxes.get(i).isSelected()) {
                    System.out.println(checkboxes.get(i).getText() + " was deleted");
                    checkboxes.remove(i);       
                }
            }   
        } 
    }

    public static void main(String[]args) { 
        JFrame frame = new JFrame();
        frame.add(new CheckBoxTest());
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.pack();
        frame.setSize(400,250);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

Upvotes: 2

Views: 97

Answers (2)

M A
M A

Reputation: 72844

Use an Iterator to loop over your checkboxes and remove an element concurrently. It is a good practice for such a use case.

for(Iterator<JCheckBox> iterator = checkboxes.iterator(); iterator.hasNext();) {
    JCheckBox checkbox = iterator.next();
    if (checkbox.isSelected()) {
        System.out.println(checkbox.getText()
                + " was deleted");
        iterator.remove();
    }
}

Upvotes: 3

Joop Eggen
Joop Eggen

Reputation: 109547

checkboxes.remove(i);       
--i;

You forgot to stay with the right i.

Upvotes: 2

Related Questions