I was able to serialize my most basic GUI object containing JTextArea and a few buttons into a test.ser file.
Now I would like to completely restore the previously saved state from test.ser, but it seems to misunderstand how to properly deserialize the state of objects.
The MyFrame class creates a JFrame and serializes it.
public class MyFrame extends JFrame implements ActionListener {
JTextArea textArea;
String title;
static MyFrame gui = new MyFrame();
private static final long serialVersionUID = 1125762532137824262L;
public static void main(String[] args) {
gui.run();
}
public MyFrame() {
}
public MyFrame(String title) {
}
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);
JButton saveButton = new JButton("Save");
saveButton.addActionListener(this);
JButton loadButton = new JButton("Load");
loadButton.addActionListener(this);
panel_02.add(loadButton);
panel_02.add(saveButton);
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) {
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent ev) {
System.out.println("Action received!");
gui.serialize();
}
}
Here I am trying to do 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) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
Can someone please point me to the direction in which my error is?
How do you guys write a class that deserializes and restores previously serialized gui elements to their previously serialized state?
The way I am doing this now seems to have several flaws in his concept, right?