PDA

Click to See Complete Forum and Search --> : Saving a Panel


amani
Apr 4th, 2002, 04:51 PM
I have a very interesting Question for you guys. I want to save the JPanel along with its contents to the disk and open it when ever need. It’s like saving the form in VB and opening the form. But in my case it is a JPanel. I used a JFileChooser to obtain a open and save dialog box. Any help in this regard is greatly appreciated.


Amani.:confused:

crptcblade
Apr 4th, 2002, 05:51 PM
Here's a simple example of how to use Serialization. I'm afraid I'm horrible at commenting, so if you have questions, just ask.

:)


import java.io.*;
import java.util.*;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.event.*;

class Test extends JFrame implements ActionListener
{
Container c;

JPanel pnlMain = new JPanel();
JButton cmdTest = new JButton("Test");

ObjectInputStream ois = null;
ObjectOutputStream oos = null;

public Test(String fileName)
{
super();
c = this.getContentPane();
c.setLayout(new GridLayout(1,1));

this.setBounds(100,100,200,200);

if (!fileName.equals(""))
{
try
{
ois = new ObjectInputStream(new FileInputStream(fileName));
pnlMain = (JPanel)ois.readObject();
ois.close();
c.add(pnlMain);
}
catch(Exception e){ System.out.println(e); }
}
else
{
pnlMain.add(cmdTest);
c.add(pnlMain);
}
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
try
{
oos = new ObjectOutputStream(new FileOutputStream("test.ser"));
oos.writeObject(pnlMain);
oos.close();
}
catch(Exception e){ System.out.println(e); }

System.exit(0);
}
});
}




public void actionPerformed(ActionEvent ae){}

public static void main(String[] args)
{
if (args.length > 0)
(new Test(args[0])).setVisible(true);
else
(new Test("")).setVisible(true);
}
}