DocumentFilter不侦听更改时该怎么办? [英] what should I do when DocumentFilter not listening for changes?

查看:82
本文介绍了DocumentFilter不侦听更改时该怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

      AbstractDocument d = (AbstractDocument)editorText.getDocument();
      d.setDocumentFilter(new myFilter());

其中editorText是JTextArea.并且我的DocumentFiler定义如下:

where editorText is a JTextArea. and my DocumentFiler is defined as follows :

private class myFilter extends DocumentFilter{
       public void insertString(DocumentFilter.FilterBypass fb,
               int offset,
               String string,
               AttributeSet attr){
           System.out.print("insert invoked");
                 try {
                    super.insertString(fb, offset, "; You inserted the string: "+string, attr);
                } catch (BadLocationException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
       }
       public void replace(DocumentFilter.FilterBypass fb,
               int offset,
               String string,
               AttributeSet attr){
           System.out.print("replace invoked");
             try {
                super.insertString(fb, offset, "; You inserted the string: "+string, attr);
            } catch (BadLocationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
       }
   }

我希望代码按如下方式工作:如果键入了一个字符,则可以预期必须触发insertString函数,并且必须在屏幕上看到的是;您插入了字符串:.不是这种情况.我该怎么做才能使程序在按下的每个字符上启动并处理并显示在屏幕上?

I want the code to work as follows: If a character is typed, then what is expected is that insertString function must fire, and what must be seen on the screen is ;you inserted the string: . This is not the case. What should I do to make the program fire on every character pressed and process it and display on screen?

推荐答案

检查是否覆盖"了

Check if you "override" all methods of DocumentFilter in the way you need. At least in the method replace(...) I noticed that you missed the int length parameter. I suggest to change it to:

public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String string, AttributeSet attr){
  System.out.print("replace invoked");
  try {
    super.insertString(fb, offset, "; You inserted the string: "+string, attr);
  } catch (BadLocationException e) {
    e.printStackTrace();                                                                                                                                                            
  }                                                                                                                                                                                   
}    

这篇关于DocumentFilter不侦听更改时该怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆