2016-02-06 90 views
0

我有以下代碼:文件偵聽多個文本字段

private void filter2method() { 

    filterR.getDocument().addDocumentListener(new DocumentListener() {//currently the document listener is set for textfield called filterR1 

      @Override 
      public void insertUpdate(DocumentEvent e) { 
       newFilter(); 
      } 

      @Override 
      public void removeUpdate(DocumentEvent e) { 
       newFilter(); 
      } 

      @Override 
      public void changedUpdate(DocumentEvent e) { 
       newFilter(); 
      } 

      private void newFilter() { 
       RowFilter <DefaultTableModel, Object>rf =null; 
       List<RowFilter<Object,Object>> rfs = 
         new ArrayList<RowFilter<Object,Object>>(); 

       ArrayList textAL = new ArrayList(); 
       String text = filterR.getText(); 
       textAL.add(text); 
       String text1 = filterR1.getText(); 
       textAL.add(text1); 
       String text2 = filterR2.getText(); 
       textAL.add(text2); 


       try { 
        for (int i = 0; i < textAL.size(); i++) { 
         rfs.add(RowFilter.regexFilter("(?i)" + textAL.get(i), 2, 6, 11)); 
        } 

        rf = RowFilter.andFilter(rfs); 

       } catch (java.util.regex.PatternSyntaxException e) { 
        return; 
       } 

       sorter.setRowFilter(rf); 
      } } 

    ); 
} 

目前的文檔偵聽設置爲文本框filterR但我想聽衆還包括filterR1和filterR2因爲我有一個搜索過濾器進一步向下搜索文本字段filterR1和filterR2的代碼,即組合的過濾器搜索。

如何更改我的文檔偵聽器以覆蓋多個文本字段?

回答

2

嗯,你可以指定DocumentListener給一個變量

DocumentListener docListener = new DocumentListener() { 
... 
}; 

而且使用它爲您的所有文本框

filterR.getDocument().addDocumentListener(docListener); 
filterR1.getDocument().addDocumentListener(docListener); 
filterR2.getDocument().addDocumentListener(docListener); 

...

+0

非常感謝偉大工程:) – Ingram