How do I implement backup and restore using serialisation with multiple classes?

后端 未结 1 407
小蘑菇
小蘑菇 2021-01-28 11:57

Im trying to serialise objects(Names and notes) which I store in my JTable. I want to be able to save this information to a file and when I load the program, the information sho

相关标签:
1条回答
  • 2021-01-28 12:27

    You appear to be doing things backwards. i.e.,

    • You should serialize not de-serialize when you back up.
    • You should do the opposite when you restore.
    • And you appear to be doing this completely backwards by calling deserialize in your backup button's ActionListener and serialize in your class creation code.
    • Edit: Also, you're serializing an object of custom type List but are never adding data from your table's model to List. So List will never hold relevant data, and so your serialization will be futile. Instead either serialize the DefaultTableModel, or transfer the model's data to the List object before serializing it.

    Also, unrelated but I feel important advice:

    • You should test complex new concepts in very simple program at first, one without a GUI, one without all this unrelated and unnecessary complexity. So get rid of your GUI and get your serialization and deserializaation working first, and only then incorporate it into your greater and more complex program with the GUI.
    • You should not use a null layout and calling setBounds(...) on your components to place them with absolute positioning as this makes for very inflexible GUI's that while they might look good on one platform look terrible on most other platforms or screen resolutions and that are very difficult to update and maintain. Instead you will want to study and learn the layout managers and then nest JPanels, each using its own layout manager to create pleasing and complex GUI's that look good on all OS's.
    • You will want to rename your custom List class so that it's name doesn't conflict with the important java.util.List class.

    Edit
    You ask in comment:

    So once the data has been entered into the JTable, it should be transfered to the list object before serialization? How would I go about doing this?

    What I would do would be to get rid of the List class entirely, I would pass the Table's model into my serialize method, I would call getDataVector() on my DefaultTableModel object to extract its nucleus, and I would serialize that.

    When de-serializing, I'd do the opposite -- read in the Vector from the disk and create a new DefaultTableModel object from it, from a Vector<String> that holds the table's column headings. As for the code details, well that's for you to work out.

    0 讨论(0)
提交回复
热议问题