Java JCheckBox ArrayList help needed

Posted by user2929626 on Stack Overflow See other posts from Stack Overflow or by user2929626
Published on 2013-10-28T21:09:57Z Indexed on 2013/10/28 21:53 UTC
Read the original article Hit count: 161

I'm new to Java and struggling with something which I'm sure must have a simple answer but I can't seem to find it. I have an array of checkbox objects defined as:

ArrayList<JCheckBox> checkBoxList

A JPanel is created with a grid layout and the checkboxes are added to the JPanel and the ArrayList:

for (int i = 0; i < 256; i++) {
    JCheckBox c = new JCheckBox();
    c.setSelected(false);
    checkBoxList.add(c);
    mainPanel.add(c);
 }

Yes, there are 256 checkboxes! The panel is added to a JFrame and eventually the GUI is displayed. The user can select any combination of the 256 checkboxes.

My class implements Serializable and this ArrayList of checkboxes can be saved and restored using 'Save' and 'Load' GUI buttons. My code to load the saved object is as below:

public class LoadListener implements ActionListener {

    public void actionPerformed(ActionEvent a) {

        try {

            // Prompt the user for a load file
            JFileChooser fileLoad = new JFileChooser();
            fileLoad.showOpenDialog(mainFrame);

            // Create a object/file input stream linking to the selected file 
            ObjectInputStream is = new ObjectInputStream(new FileInputStream(fileLoad.getSelectedFile()));

            // Read the checkBox array list
            checkBoxList = (ArrayList<JCheckBox>) is.readObject();              
            is.close();

        } catch (Exception ex) {

            ex.printStackTrace();

        }

    }

On loading the ArrayList object, the values of the checkboxes are correctly populated, however I want to update the checkboxes on the GUI to reflect this. Is there an easy way to do this? I assumed as the array of checkboxes had the correct values that I could just repaint the panel / frame but this doesn't work. I'd like to understand why - does my loaded array of checkbox objects no longer reflect the checkbox objects on the GUI? Any help would be much appreciated.

Thanks!

© Stack Overflow or respective owner

Related posts about java

Related posts about swing