gpt4 book ai didi

java - 从文档监听器返回一个值

转载 作者:行者123 更新时间:2023-12-01 05:00:44 25 4
gpt4 key购买 nike

我有 2 个 Java 类(class)。一旦将文档监听器添加到文档(HTMLDoc)。另一个是实现 DocumentListener 的类。

我希望能够向此类返回一个值,以便我知道文档何时更改,这样我就可以删除粘贴到其中并导致 JTextPane 出现问题的不需要的 html。

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

最佳答案

看看DocumentFilter 。它允许您在将文本写入文档之前重新格式化文本。

关于java - 从文档监听器返回一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13421910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com