如何在动作侦听器中检查动态生成的 JCheckBox 的状态

How to check the state of a dynamically generated JCheckBox in an action listener

我创建了链接到文件的动态 JChekboxes。我想看看哪些是通过动作侦听器检查的。我试过 getSource(),我试过 getState() none 它们正在工作...

for (int f = 0; f < numberCheckBox[0]; f++) {
            String line1 = tableLines[f].toString().trim();
            String[] dataRow1 = line1.split("/");
            checkBoxList[f] = new JCheckBox(Arrays.toString(dataRow1).replace("[", "").replace("]", ""));
            Checkp.add(checkBoxList[f]);
            System.out.print(checkBoxList[f]);
        }

         save.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            BufferedReader br = null;
            try {
                br = new BufferedReader(new FileReader(files));
                Object[] tableLines = br.lines().toArray();
                numberCheckBox[0] = tableLines.length;
                for (int j = 0; j < numberCheckBox[0]; j++) {
                    if(e.getSource() == finalCheckBoxList[j]){
                        if(e.getStateChange() == 1){

                        }
                    }
                }
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            }

您要做的第一件事就是查看 How to Use Buttons, Check Boxes, and Radio Buttons

所以从 JCheckBox JavaDocs

isSelected

public boolean isSelected()

Returns the state of the button. True if the toggle button is selected, false if it's not.

Returns:
true if the toggle button is selected, otherwise false

此外,如果您需要某种方式将信息传递给ActionListener。您可以继续依赖值的 index,但如果可能,我总是更喜欢封装此信息。

所以,在这个例子中,我使用了 actionCommandclientProperty 方法来播种我可能想在 ActionListener

中使用的信息

I did use isSelected and it did not work as well.

那么你做错了什么,因为下面的例子工作得很好

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {

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

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());

            int[] numberCheckBox = new int[] { 5 };
            JCheckBox[] checkBoxList = new JCheckBox[5];
            String[] tableLines = new String[] {
                "this/is/a/test",
                "hello/world",
                "something/wicked/this/way/comes",
                "a/long/long/time/ago",
                "i/have/something/to/say",
            };

            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = gbc.REMAINDER;
            gbc.anchor = GridBagConstraints.LINE_START;
            for (int f = 0; f < numberCheckBox[0]; f++) {
                String line1 = tableLines[f].toString().trim();
                String[] dataRow1 = line1.split("/");                
                checkBoxList[f] = new JCheckBox(String.join(", ", dataRow1));
                checkBoxList[f].setActionCommand(line1);
                checkBoxList[f].putClientProperty("value", line1);
                add(checkBoxList[f], gbc);
                System.out.print(checkBoxList[f]);
            }

            JButton save = new JButton("Save");
            gbc.anchor = GridBagConstraints.CENTER;
            add(save, gbc);

            save.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    for (JCheckBox cb : checkBoxList) {
                        if (cb.isSelected()) {
                            System.out.println("Action Command = " + cb.getActionCommand());
                            System.out.println("Client Property = " + (String)cb.getClientProperty("value"));
                        }
                    }
                }
            });
        }
    }
}