NotSerializableException when using DefaultComboBoxModel in another class

106 Views Asked by At

I'm working on a big school project and it's coming to an end. I want 2 JComboBoxes to be synchronized at the different classes(JPanels) in my program, and after not knowing much about how JComponents works I found out that it's not the JComboBox itself that holds the data, but the ComboBoxModel.

So after adding a DefaultComboBoxModel to my Register (the class that holds all my data), and sharing it to my other two JPanels, it's finally working.

But now I get the NotSerializable when writing my Register-class to file. (I've been taking DefaultComboBoxModel out of my Register class and got everything back to working again, so I know that's the problem).

What I can see in the documentation, DefaultComboBoxModel implements Serialiazble, and so does my objects that the Model holds.

public class Register implements Serializable
{
    ...
    private DefaultComboBoxModel klippPriser;

    public Register()
    {
        ...
        Object[] antTurer = { new KlippPris(5,0), new KlippPris(10,0.05), new KlippPris(15,0.10) };
        klippPriser = new DefaultComboBoxModel(antTurer);
    }

    public DefaultComboBoxModel getKlippPriser()
    {
        return klippPriser;
    }

My guess is that it's not possible to use the DefaultComboBoxModel as a list to store objects in and write to file, but I'm not really sure how to solve it and still keep my program dynamic.

I hope I made my problem clear. Thanks.

EDIT2: The KlippPris class that the model holds. (ISNT THE PROBLEM)

public class KlippPris implements Serializable
{
    private int antall;
    private double rabatt;

    ...
}

EDIT3: Found out that the problem is NOT in Register, but in Salg and Administrasjon. Can't really figure out why tho...

Salg.java (Administrasjon using kinda the same lines.)

public class Salg extends JPanel
{
    private Register register;
    ...
    private JComboBox antTurer;

    public Salg(Register r)
    {
        super();
        register = r;
        gui();
    }

    private void gui()
    {
        ...
        paintKortkjøp();
        ...
    }

    private void paintKortkjøp()
    {
        ...
        // This line cause the exception.
        antTurer = new JComboBox(register.getKlippPriser());

        // This line dosen't cause any problems, but won't let my use my model.
        antTurer = new JComboBox();
    }

Why is this happening? I'm not writing neither Salg or Administrasjon to file, just the Register. I've also tried setModel() without no luck.

Not sure if the exception means anything:

com.apple.laf.AquaComboBoxUI

Java v.6, Mac OSX 10.8.3.

1

There are 1 best solutions below

11
On

In order for an object to be serialized, it must not only implement Serializable but all class members should be serializable also. Any fields that do not need to be serialized can be declared as transient:

private transient MyUnwrittenType type;