Java 重复调用DocumentListener方法
我制作了一个documentlistener,在插入文本时调用一个方法。它可以工作,但问题是它的行为就像在一个循环中一样,并且一直被调用。Java 重复调用DocumentListener方法,java,swing,loops,invokelater,swingutilities,Java,Swing,Loops,Invokelater,Swingutilities,我制作了一个documentlistener,在插入文本时调用一个方法。它可以工作,但问题是它的行为就像在一个循环中一样,并且一直被调用。 该方法从方法内部使用swingutilites.invokelater private void addNewLine() { SwingUtilities.invokeLater( () -> { textArea.append(System.getProperty("line.separator")+"hey")
该方法从方法内部使用swingutilites.invokelater
private void addNewLine() {
SwingUtilities.invokeLater( () -> {
textArea.append(System.getProperty("line.separator")+"hey");
});
}
private final DocumentListener addNewLine = Handlers.forDocumentUpdate((event) -> {
addNewLine();
});
@SuppressWarnings("serial")
static DocumentListener forDocumentUpdate(Consumer<? super DocumentEvent> eventHandler) {
return new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent event) {
eventHandler.accept(event);
}
@Override
public void removeUpdate(DocumentEvent event) {
}
@Override
public void changedUpdate(DocumentEvent event) {
}
};
}
private void addNewLine(){
SwingUtilities.invokeLater(()->{
append(System.getProperty(“line.separator”)+“hey”);
});
}
private final DocumentListener addNewLine=Handlers.forDocumentUpdate((事件)->{
addNewLine();
});
@抑制警告(“串行”)
静态DocumentListener for DocumentUpdate(Consumer在我使用DocumentListener执行此任务之前,但递归循环存在问题。正确的方法是添加DocumentFilter,它将简单地添加一个换行符以及插入要插入的原始文本的代码
((AbstractDocument) textArea.getDocument()).
setDocumentFilter(new NewLineFilter());
public class NewLineFilter extends DocumentFilter {
@Override
public void insertString(FilterBypass fb,int offs,String str,AttributeSet a)
throws BadLocationException {
}
@Override
public void replace(FilterBypass fb, int offs,int length, String str, AttributeSet a)
throws BadLocationException {
System.out.println("in replace");
super.replace(fb,offs,length,str,a);
super.insertString(fb, fb.getDocument().getLength(), System.lineSeparator(), a);
}}
如果你知道一个更好的方法来写这个,或者如果你知道一个可以为这个创建匿名类的处理程序,那就太好了。我不能使用Consumer,因为replace()有不止一个参数。我可以创建另一个函数接口,但我不知道它有多有用。我想如果我需要再次使用同一个类,可能只需重新使用该类。Post a..不要从DocumentListener
中更新文档,这可能会导致变异异常,或者,正如您所看到的那样o发现了其他不寻常的行为。相反,考虑使用<代码>文档过滤器>代码>,而不是试图找到一个“工作”。对于你的问题,首先用最好的工具来解决它,看看,通过TransferHandler来完成这项工作是一种浪费,因为当我真的想运行一行代码时,我不得不重写很多代码。我试着通过TransferHandler来完成这项工作。我对documentfilter不是很熟悉,但是t我会看一看。我认为如果它可以潜在地忽略过滤器所做的任何更改,可能会更好。