У меня есть 2 класса Java. Один раз добавляет прослушиватель документов в документ (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
DocumentListener
, но в вашем вопросе это плохо показано. - person Roman C   schedule 17.11.2012