I am working on a Swing application for data maintenance (Java 6). There is a JFrame with several JTextFields. If the user is editing a record, there is UNSAVED data until she/he presses the Save-Button.
The application should always be aware if there is unsaved data. How can this be done?
You could keep a boolean around that indicates whether there is unsaved data. Initially it would be false, but would be set to true in a key listener attached to each field.
(The logic in the key listener could be a bit more elaborate, like detecting if the new value is actually different from the last saved value. E.g., typing a key, and then hitting delete, should not count as a change in this context.)
Once the data is saved, the boolean is reset to false.
A possible solution is: after each keystroke I compare the new content of JTextField with the stored old string. If there is a difference I set the "changed"-flag.
Does this make sense or is there a better way?
Best regards Gerald
Joined: Mar 22, 2005
Well, if you really want to take the old, saved value into account, then you'd need a "changed" flag for each textfield. The overall "changed" status would then be the logical OR of all individual flags.
If you have just a single flag, then you can't take individual field's changed/unchanged status into account.
Consider these two cases: 1) field A changes, then field B changes, then A changes back to its original value, and 2) field A changes, then A changes back to its original value. The warning "you have unsaved changes" (or whatever the code is going to do) should be shown for case 1, but not for case 2. But these cases can't be distinguished with just a single flag.
Joined: Jul 23, 2007
Thank you again!
I'll think it over.
But isn't there a standard solution to this (common) task?
this might be one way, flag is set on any keystroke - modify to suit. e.g. 1) type some text, click save, exit - exits without warning 2) type some text, click save, ctrl-c to copy the text, exit - warning displays
Joined: Jul 23, 2007
you've answered my next question: How can I prevent data loss when closing the application?