简体   繁体   English

如果选中某个JCheckBox,如何删除它?

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

I am using an Arraylist for my Checkboxes. 我正在为我的复选框使用Arraylist 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. 正如其他人在注释部分中指出的那样,您不应删除ArrayList项,因为不会获得预期的结果。

You should use an Iterator instead. 您应该改用Iterator

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. 使用现代的Collection API。

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

Or use a method reference. 或使用方法参考。

SBName.removeIf(JCheckBox::isSelected);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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