Search code examples
javaimageiconobjectinputstreamobjectoutputstream

Can I save ImageIcon with ObjectOutputStream?


Does anybody know if you can save an ImageIcon file with ObjectOutputStream? I have a person-registry that I save with an ObjectOutputStream, So it would be really convenient to to write the the imageicon together with that information. But when I try to read the image icon, nothing happens. I get to read all the other information but cant seem to get the ImageIcon.

Anybody got any ideas to what I can do?

EDIT: I have a person class and a person registry class. below is the person class and the personregistry class is just a collection of several persons. i write out the person-registry with objectoutput stream.

public Person(String fn, String en, String a, int t, ImageIcon kb, Kort k)   {
        fname= fn;
        lname= en;
        adress= a;
        tlf= t;
        card= k;
        df.format(medlemsNr= ++nextNr);
        cardPicture= kb;
        neste= null;
    }

public void writePersonsToFile()   {
        try(ObjectOutputStream utfil= new ObjectOutputStream(
                new FileOutputStream(("PersonRegistry.data"))))   {
            utfil.writeObject(personRegistry);
        }
        catch(NotSerializableException nse) {

        }
        catch(IOException ioe)  {

        }
    }

Solution

  • I solved it at last. It was a stupid mistake on my hand. It worked fine to save the ImageIcon through ObjectOutputStream and in again. The trouble was with the file I tried to save.

    The ImageIcon that I wanted to save was inside a JLabel on the GUI. To save it, I had to get the Icon first with:

    ImageIcon imgIcon= (ImageIcon)imgLabel.getIcon();
    

    and then run it through the outputstream. Thanks for all help. =)