Restaurar o objeto JFrame serializado anteriormente, como?
Eu consegui serializar meu objeto GUI muito básico contendo um JTextArea e alguns botões para um arquivo 'test.ser'.
Agora, eu gostaria de restaurar completamente o estado salvo anteriormente de 'test.ser', mas parece ter um conceito errado de como desserializar adequadamente um estado de objetos.
A classeMyFrame cria o JFrame e o serializa.
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();
}
}
Aqui eu tento fazer a desserialização:
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();
}
}
Talvez alguém possa me indicar a direção em que está meu equívoco?
Como vocês escreveriam uma classe, que desserializa e restaura os elementos-gui serializados anteriormente para o estado serializado anteriormente?
A maneira como estou fazendo isso agora parece ter mais de uma falha em seu conceito, certo?