我有 2 个 java 类。一旦将文档侦听器添加到文档(HTMLDoc)。另一个是实现 DocumentListener 的类。
我希望能够向此类返回一个值,以便我知道文档何时更改,以便我可以删除不需要的 html,这些 html 被粘贴并导致 JTextPane 出现问题。
doc = (HTMLDocument) kit.createDefaultDocument();
//setContentType("text/html");
doc.addDocumentListener(new CTextPaneListener());
这是监听器类
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