如何知道jtextarea是否有任何变化?(How to know whether any changes in the jtextarea have been made or not?)
我创建了一个jtextarea,用户可以在其中修改其内容。 我想知道,如果有任何办法,用户是否在关闭应用程序之前修改了其内容。 请帮忙。 -提前致谢
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
最满意答案
您需要将DocumentListener添加到支持文本区域的Document 。
然后在侦听器的回调方法(insertUpdate(),removeUpdate(),changedUpdate())中,只需设置一个标记即某些内容已更改并在关闭应用程序之前测试该标志
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; } }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; } }更多推荐
发布评论