我有2个java类。将文档侦听器添加到doc(HTMLDoc)后。另一个是实现DocumentListener的类。
我希望能够为此类返回一个值,以便我知道文档何时更改,以便我可以删除粘贴的不需要的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