Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 621
Antrromet Avatar asked Dec 16 '22 17:12

Antrromet


2 Answers

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;
  }
}
like image 51
a_horse_with_no_name Avatar answered Dec 28 '22 08:12

a_horse_with_no_name


Save the value of jtextarea and compare this value to the value of jtextarea in the moment of application closing.

Pseudocode here, doesn't remember the excact syntax of text area:

String oldText = textarea.getText();
....

// not the exact method, just to point the moment of application exit 
public onClose() {

  String newText = textArea.getText();
  // assuming oldText is not null
  if (oldText.equals(newText)) {
     // no changes have been done
  } else {
   // the value changed
  }

}
like image 22
Vladimir Ivanov Avatar answered Dec 28 '22 06:12

Vladimir Ivanov