简体   繁体   中英

Java Serializable Object fails

I am having an issue with writing a Serializable object to a file. I have been able to narrow the problem down, but have no idea what would cause this, so I'm just looking for advice anyone may have, because I can't really give an example, but I will give some shell code to paint the picture.

Basically I have an object storing information about the program that I save by writing the object to file. It has a DefaultComboBoxModel which is part of what is causing my issue. For example:

public class ProgramInfo implements Serializable {
     private DefaultComboBoxModel model = new DefaultComboBoxModel();
     // A bunch of other stuff

     public DefaultComboBoxModel getModel() {
         return model;
     }
     public void setModel(DefaultComboBoxModel m) {
         model = m;
     }
}

Then, I have a class which extends JPanel and looks like this:

public class SomePanel extends JPanel {
    private SomeOtherClass someOtherClass = new SomeOtherClass();
    private ProgramInfo programInfo;
    // A bunch of other stuff

    public SomePanel(ProgramInfo info) {
        programInfo = info;
        initGUI();
    }

    private void initGUI() {
        JComboBox box = new JComboBox(programInfo.getModel());
    }
}

The issue occurs after I add an element to DefaultComboBoxModel by calling model.addElement(). However, the issue does not occur if I only have one instance of SomePanel in my program, but if I create a second instance of SomePanel, it throws a java.io.NotSerializableException on the object SomeOtherClass when trying to write ProgramInfo to file. If I comment out SomeOtherClass, then the next object in the SomePanel class throws the same error when trying to write ProgramInfo to file.

As a note, I am not an expert programmer, it is just a hobby and I am completely self taught. Any advice/reading material on why this could happen would be great. Thanks in advance!

Fields must also be serializable so you should check if DefaultComboBoxModel implements Serializable . I suspect it does not.

You should see this as a reference for Serialization of an object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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