I am making program in Java in which I am making Dialog box
, button
, checkbox
, etc. SWT widgets.
Now my problem is, I want like if in one execution button
is made and in second execution checkbox
is made then they both should display in one box.
So I need to store that box object.
How can I do that?
5
In general, there are two ways to go about doing what you need:
- Store the state of the object, and
- Store the sequence of commands that lead the object to its current state
The first way is addressed by externalization of an object’s state. Essentially, you write to an external storage of some sort a file with a description of the current state of the object:
Label at 40,10 text "Are you sure?"
Button at 40,20 size 30,10 text "OK"
Button at 40,40 size 30,10 text "Cancel"
You can read this file and restore the object to its current state.
The second way is addressed by storing commands, like this:
Add Label id 123 at 0,0
Move id 123 to 40,15
Set text id 123 "Are you crazy?"
Move id 123 to 40,10
Add Button id 124 at 0,0
Set text id 124 "Cancel"
Move id 124 to 40,40
Add Button id 125 at 0,0
Set text id 125 "OK"
Move id 125 to 40,20
Set text id 123 "Are you sure?"
When you have a file like that, you can “replay” it to get the current state of your object. But more importantly, you can use it to implement “undo” that survives exiting the application. If you add timestamps to the events, you would also get a way to restore the state as of some time in the past.
Basically you have to do this yourself. There are many ways to “persist” data and you’re free to use any of them. You have to choose where the data will be stored first:
- On the local computer
- On a server on the local network
- On a server somewhere on the internet?
…and you have to decide what format:
- CSV file
- Binary serialized file (Java serialization)
- Database
If you choose a Database, there are various frameworks like Hibernate that can help you.
So, when your application closes you have to hook that event and run some code that takes the program state you want to store and somehow gets it into your persistent storage. Then when the application starts up you have to open that storage, load the data, and rebuild the GUI the way you want it to be.
2