简体   繁体   中英

Java: What is the best way to read a Serialized object?

I apologize in advance if I am repeating a question. If I am, please forward me to the relevant post.

I have a JPanel which has quite a few components on it. This is then placed onto a JFrame. I would like to give the user an opportunity to save their current session (ie Serialize the JPanel with its subcomponents values intact). The user should then have the opportunity to load up a previous session (which is basically that JPanel with the saved selection of comboxes & text field entries).

My question pertains to the reading of the JPanel object from a file. Once I read the JPanel from a file, do I have to read each and every one of its text fields and comboboxes or can I simply replace my JPanel with the saved JPanel? As far as I can work out, the only way to do this is to replace the current panel with the saved panel like this:

  • 1: MyPanel savedPanel = (MyPanel)objectInputStream.readObject();
  • 2: remove(currentPanel);
  • 3: add(savedPanel);
  • 4: validate();

Is this there any to achieve what I want?

Thank you.

De-serialization restores the object graph that was saved. However see the Javadoc: it really isn't recommended to serialize Swing objects. You might look into java.beans.XMLEncoder .

Save the data backing the Swing panel, not the panel itself. The panel is presentation, not user data - you should be able to rebuild the state of the panel based on the user data alone.

To that end, create a Model which models the panel's data model, and then look into an XML or JSON serialiser that will allow you to persist and retrieve the data for the model. Populate the UI from the model and you give yourself the ability to store and refresh the screen from a single, well-contained point in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM