Search code examples
javaobjectsavejcheckbox

Saving newly created objects in java


Sorry to keep bugging you guys but I've run into another problem with my program. I can't save my newly created check boxes without getting multiple errors. Basically, I made it so the program generates a new check box whenever you type in whatever you want to name it but the save button I've added isn't saving the program as intended. I'd like to save list and be able to come back and modify it should the need arise.

Here are the parts in question that are giving me a hard time. Sorry about the poor formatting.

This is largely from an older post and if you scroll down, you will see the saving code.

package appchecklist;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;

import javax.swing.*;

public class List {
    public JPanel panel = new JPanel();
    Scanner input = new Scanner(System.in);
    public List() {
        JButton button = new JButton("Add checkbox");
        JButton save = new JButton("Save program");             
        JButton load = new JButton("load program");
        panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                panel.add(new JCheckBox(input.nextLine()));
                    if (input == null) {
                        System.out.println("Please enter a name for a checkbox");
                    }                           

                    panel.revalidate();
                    panel.repaint();
                    SwingUtilities.windowForComponent(panel).pack();
                }
            });

            save.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    new SaveButton();               
                }   
            });             

            load.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) { 
                    new Loadbutton();
                }   
            });             
            panel.add(button);  
            panel.add(save);
            panel.add(load);
        }
    }
}

package appchecklist;
import java.io.*;

public class SaveButton{
    public SaveButton() {
        List savedata = new List();
        try {
            FileOutputStream saveFile = new FileOutputStream("Checklist.java");
            ObjectOutputStream save = new ObjectOutputStream(saveFile);
            save.writeObject(savedata);
            save.close();
        } catch (Exception exc){ exc.printStackTrace(); }
    }
}  

Solution

  • Your List class is not serializable. Just change

     public class List {
    

    to

     public class List implements Serializable{
    

    For more information, see the documentation on Serializable. It is posible to customize the serialization.