Results 1 to 2 of 2

Thread: Saving a Panel

  1. #1
    amani
    Guest

    Saving a Panel

    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.

  2. #2
    The Devil crptcblade's Avatar
    Join Date
    Aug 2000
    Location
    Quetzalshacatenango
    Posts
    9,091
    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.



    Code:
    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);
    	}	
    }
    Laugh, and the world laughs with you. Cry, and you just water down your vodka.


    Take credit, not responsibility

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width