Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

I have created dynamic JChekboxes that is linked to a file. I want to see which ones are checked via an action listener. I have tried getSource(), I have tried getState() none of them are working…

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The first thing you’ll want to do is check out How to Use Buttons, Check Boxes, and Radio Buttons

So from the 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

In addition, if you need some way to pass information to the ActionListener. You could continue to rely on the index of the values, but I always prefer to encapsulate this information if possible.

So, in this example, I’ve used both the actionCommand and clientProperty methods to seed the information I might want to use in the ActionListener

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

Then you’re doing something wrong, because the below example works just fine

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"));
                        }
                    }
                }
            });
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading