The most robust way would be to keep a String lastSaved
object.
When you do save()
do:
lastSaved = textArea.getText();
Then in your textAreaKeyTyped()
do:
boolean unchanged = textArea.getText.equals(lastSaved);
if (!unchanged) {
// add *, enable save, etc
} else {
// remove *, disable save, etc
}
This will have the added benefit that if a user reverses their changes their document will go back to a "not modified" state.
I would actually create a method updateSaveState()
containing that code and have both save and the modified callback call updateSaveState()
, removing the duplicated code there and putting all the logic for window title etc in one place.
I'd also be tempted to create an isModified()
method that returns !textArea.getText.equals(lastSaved)
and remove the saved flag completely. Anything that wants to know can just call isModified()
.
Note that in this case the edit will not be applied yet at the point the keyTyped is received. If you do a SwingUtilities.invokeLater
to delay your processing until after the keypress has been processed that should fix this problem.