Friday 11 January 2008

Checking if a JEditorPane has been edited (changed)

While I was looking for a way to check if a JEditorPane's text had been changed since the last save, I found a site that actually wanted me to pay for the answer. Bloody cheek. It isn't that tough, but it took a bit of reading. All that is needed is to install a DocumentListener into the editor pane's document. You can download a complete example swing-editor-src-0.1.jar which includes an ant build file. Just type "ant run" at the shell prompt to run it. You will need ant and JDK >= 1.5 (it may work in older JDKs, but I used 1.5 so I can't be sure).

The document can't tell when your program has saved the document (ie, it is no longer "dirty"), so you need to call setDirty(false) after a save.

2 comments:

Mike Wilson said...

The files have moved to my new Drupal site. Please visit http://projects.babblemind.com/node/26 for the downloads.

N_Inhoffen@web.de said...

Thanks, very helpful solution. You were so kind as to point out that the document listener needs being told that the document was saved. It might be worthwhile adding a note on the fact that the document listener has to be re-registered each time a new document is loaded into the editor. Logic, since the listener is registered with the document, not with the editor, but a bit tricky for newbies like me. In practical use the code needs some adjustment (a speparate public method for adding the DocumentListener).