Checking if a JEditorPane has been edited

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 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).

  1. public class SwingEditor extends JEditorPane {
  2. private boolean dirty = false;
  3.  
  4. public SwingEditor() {
  5. super("text/plain", "");
  6. setFont(new Font("Monospaced", Font.PLAIN, 12));
  7. getDocument().addDocumentListener(
  8. new EditDocumentListener());
  9. }
  10.  
  11. public boolean isDirty() {
  12. return dirty;
  13. }
  14.  
  15. public void setDirty(boolean newDirty) {
  16. dirty = newDirty;
  17. }
  18.  
  19. private class EditDocumentListener implements
  20.  
  21. public void changedUpdate(DocumentEvent ev) {
  22. dirty = true;
  23. }
  24.  
  25. public void insertUpdate(DocumentEvent ev) {
  26. dirty = true;
  27. }
  28.  
  29. public void removeUpdate(DocumentEvent ev) {
  30. dirty = true;
  31. }
  32. }
  33. }

Source download: swing-editor-src-0_1.jar