Domanda

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?

È stato utile?

Soluzione

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();                                                                                                                                                            
  }                                                                                                                                                                                   
}    
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top