开发者

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 n开发者_StackOverflow社区ot before closing the application. Please help.

-Thanks in advance


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


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
  }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜