This page contains an archived post to the Java Answers Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Artima Forums.
Message:
Try this out!!
Posted by Manpreet Minhas on January 29, 2002 at 7:04 AM
Hi Avin! Hope this code is of some help to you. I have made a sample application for you. You can pick up the required code from it and use it accordingly class Test extends JFrame implements ActionListener { JButton newButton, saveButton,button; Panel panel, southPanel; public boolean checkFile() { try { File ob = new File("state.txt"); if(ob.exists()) { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(ob)); panel =(Panel) ois.readObject(); ois.close(); return true; } else return false; } catch(Exception e) { e.printStackTrace(); return false; } } public Test() { boolean exists = checkFile(); if(!exists) { button = new JButton("Hello"); panel = new Panel(); panel.add(button); } newButton = new JButton("New Button"); saveButton = new JButton("Save State"); newButton.addActionListener(this); saveButton.addActionListener(this); southPanel = new Panel(); southPanel.add(newButton); southPanel.add(saveButton); this.getContentPane().add(panel,BorderLayout.CENTER); this.getContentPane().add(southPanel,BorderLayout.SOUTH); setSize(300,300); setVisible(true); } public void actionPerformed(ActionEvent ae) { String str = ae.getActionCommand(); if(str.equals("Save State")) { saveState(); } if(str.equals("New Button")) { panel.add(new JButton("Hello")); this.setVisible(true); } } public static void main(String args[]) { new Test(); } public void saveState() { try { FileOutputStream fos = new FileOutputStream("state.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(panel); oos.close(); System.out.println("Current state saved"); } catch(Exception e) { e.printStackTrace(); } } } In this case I have assumed that when you click on the save button a file called state.txt (or any file with a name and extension of your choice) is created on the disk which contains the state of your panel and finally when you click on the open button and your File dialog box appears you choose state.txt which opens up your saved state. This whole logic is based on the concept of Serialization as Panel is serilazable you can easily do that by saving it to the disk. I have left the GUI part i.e creating of the file dilaogs and open/save buttons to you..... You can pick up the saving logic from saveState() function and open login from checkFile() function i hope it meets your requirement.......do lemme know if it helped your purpose Warm regards! Minhas
Replies:
|