Search code examples
javaswingjtextarea

How to know whether any changes in the jtextarea have been made or not?


I've created a jtextarea where a user can modify its content. I want to know,if there is any way, whether the user has modified its content or not before closing the application. Please help.
-Thanks in advance


Solution

  • You need to add a DocumentListener to the Document that backs the text area.

    Then in the callback methods (insertUpdate(), removeUpdate(), changedUpdate()) of the listener, simply set a flag that something has changed and test that flag before closing the application

    public class MyPanel
      implements DocumentListener
    {
      private boolean changed;
    
      public MyPanel()
      {
        JTextArea textArea = new JTextArea();
        textArea.getDocument().addDocumentListener(this);
        .....
      }
    
      .....
    
      public void insertUpdate(DocumentEvent e)
      {
        changed = true;
      }
      public void removeUpdate(DocumentEvent e)
      {
        changed = true;
      }
      public void changedUpdate(DocumentEvent e)
      {
        changed = true;
      }
    }