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

眉间皱痕 提交于 2020-01-14 12:58:12

问题


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


回答1:


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;
  }
}



回答2:


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
  }

}


来源:https://stackoverflow.com/questions/4836224/how-to-know-whether-any-changes-in-the-jtextarea-have-been-made-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!