java从文档侦听器返回一个值
我有两个java类。一旦将文档侦听器添加到文档(HTMLDoc)。另一个是实现DocumentListener的类
我希望能够向这个类返回一个值,这样我就知道文档什么时候被更改了,这样我就可以去掉不需要的html,这些html会被粘贴进来,并导致JTextPane出现问题
doc = (HTMLDocument) kit.createDefaultDocument();
//setContentType("text/html");
doc.addDocumentListener(new CTextPaneListener());
这是Listener类
public class CTextPaneListener implements DocumentListener
{
// Gives notification that an attribute or set of attributes changed.
@Override public void changedUpdate(DocumentEvent e)
{
//System.out.println("DEBUG: changedUpdate() called");
}
//Gives notification that there was an insert into the document.
@Override public void insertUpdate(DocumentEvent e)
{
// I want to be able to return a value or a form a detection
// so I can tell when there has been a insert.
}
//Gives notification that there was a remove from the document.
@Override public void removeUpdate(DocumentEvent e)
{
//System.out.println("DEBUG: removeUpdate called");
}
}
我学过一点java,但已经有几年了,所以我有点生疏了。谢谢你抽出时间
编辑:这是我的自定义DocumentFilter,我原本以为这会捕获粘贴,但似乎只有DocumentListener能够捕获粘贴
public class CTextPaneFilter extends DocumentFilter
{
public CTextPaneFilter(Document doc)
{
this(doc, 0);
}
public CTextPaneFilter(Document doc, int maxChars) {
this.doc = doc;
maxCharacters = maxChars;
}
/**
* Specifies the maximum text input length of the text pane.
*/
public void setMaxLength(int len)
{
maxCharacters = len;
}
/**
* Invoked prior to insertion of text into the specified Document.
*/
@Override public void insertString(DocumentFilter.FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException
{
/**
* Teuncates the inserted string so the contents
* would be exactly maxCharacters in length.
*/
System.out.println("insert");
if (maxCharacters == 0 || (doc.getLength() + string.length()) <= maxCharacters) {
fb.insertString(offset, string, attr);
} else {
if (doc.getLength() < maxCharacters) {
fb.insertString(offset, string.substring(0, maxCharacters - doc.getLength()), attr);
}
//Toolkit.getDefaultToolkit().beep();
}
// other overridden methods below
# 1 楼答案
看看DocumentFilter。它允许您在将文本写入文档之前重新格式化文本