what should I do when DocumentFilter not listening for changes?

百般思念 提交于 2019-12-24 14:43:07

问题


Hi I have the following code :

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

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();
            }
       }
   }

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?


回答1:


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();                                                                                                                                                            
  }                                                                                                                                                                                   
}    


来源:https://stackoverflow.com/questions/20179370/what-should-i-do-when-documentfilter-not-listening-for-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!