Search code examples
javaswingserializationlook-and-feel

JFrame serialisation with LookAndFeel


I am trying to serialize a JFrame containing a JDesktopPane with several JInternalFrames. I encountered a problem with the LookAndFeel because for any reason it is not possible to serialize a Swing component with a to the CrossPlatform LnF different one. So I wrote this test program in order to figure out my possibilites:

public static void main(String[] args) {    
    try {
        JFrame f = new JFrame();
        f.setBounds(200,200,200,200);
        JTree tree = new JTree();
        f.add(tree);
        f.setVisible(true);

        UIManager.setLookAndFeel(
                   UIManager.getCrossPlatformLookAndFeelClassName());
        SwingUtilities.updateComponentTreeUI(f);

        ObjectOutputStream oop = new ObjectOutputStream(
                   new FileOutputStream(new File("test.serialized")));
        oop.writeObject(f);
    } catch(IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedLookAndFeelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

This didn't work for two reasons:

  1. I am not able to serialize the frame and the contained tree. Just the tree is fine but just when
  2. I set the LookAndFeel to cross platform in the first place and create my tree afterwards.

Any idea how to fix this?

EDIT: Sorry for making this not clear: I am NOT trying to serialize the LnF or something like that. The LnF doesnt want me to serialize the Frame.

java.io.NotSerializableException: com.apple.laf.AquaTreeUI

And on top of that i am not able to serialize a Frame that contains a Tree.

Exception in thread "AWT-EventQueue-0" java.lang.InternalError: incorrect component

Solution

  • Check this. Is the implementation proposed by @SoboLAN.