Restore previously serialized JFrame-object, how?

Posted by elementz on Stack Overflow See other posts from Stack Overflow or by elementz
Published on 2010-04-26T08:29:34Z Indexed on 2010/04/26 10:13 UTC
Read the original article Hit count: 249

Hi all. I have managed to serialize my very basic GUI-object containing a JTextArea and a few buttons to a file 'test.ser'.

Now, I would like to completely restore the previously saved state from 'test.ser', but seem to have a misconception of how to properly deserialize an objects state.

The class MyFrame creates the JFrame and serializes it.

public class MyFrame extends JFrame implements ActionListener {

// Fields JTextArea textArea; String title; static MyFrame gui = new MyFrame(); private static final long serialVersionUID = 1125762532137824262L;

/** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub gui.run(); }

// parameterless default contructor public MyFrame() {

}

// constructor with title public MyFrame(String title) {

}

// creates Frame and its Layout public void run() {

JFrame frame = new JFrame(title); JPanel panel_01 = new JPanel(); JPanel panel_02 = new JPanel();

JTextArea textArea = new JTextArea(20, 22); textArea.setLineWrap(true);

JScrollPane scrollPane = new JScrollPane(textArea);

scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);

panel_01.add(scrollPane);

// Buttons JButton saveButton = new JButton("Save"); saveButton.addActionListener(this); JButton loadButton = new JButton("Load"); loadButton.addActionListener(this);

panel_02.add(loadButton); panel_02.add(saveButton); // Layout frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(BorderLayout.CENTER, panel_01); frame.getContentPane().add(BorderLayout.SOUTH, panel_02);

frame.setSize(300, 400); frame.setVisible(true); }

/* * */ public void serialize() {

try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("test.ser")); oos.writeObject(gui); oos.close(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } }

public void actionPerformed(ActionEvent ev) { System.out.println("Action received!"); gui.serialize(); }

}

Here I try to do the deserialization:

public class Deserialize {
 static Deserialize ds;
 static MyFrame frame;

public static void main(String[] args) { try { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.ser")); frame = (MyFrame) ois.readObject(); ois.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }

Maybe somebody could point me into the direction where my misconception is? Thx in advance!

© Stack Overflow or respective owner

Related posts about java

Related posts about basic