5

I have a 12 filters for 12 columns on a JTable. Each filter is a TextField of type JTextField. Every time a user enters the data in the text box filter then search happens.

Example: Suppose say, I have 3 columns and 3 text boxes above them as filters. Now any thing which is typed in any of the text boxes my table filtering has to happen. It is happening great.

╔═════════════╦═════════════╦═════════════╗
║ [TextField] ║ [TextField] ║ [TextField] ║
╠═════════════╬═════════════╬═════════════╣
║             ║             ║             ║
╠═════════════╬═════════════╬═════════════╣
      ...           ...           ...
╠═════════════╬═════════════╬═════════════╣
║             ║             ║             ║
╚═════════════╩═════════════╩═════════════╝

Text field listener for each of the text field looks like this,

textField.getDocument().addDocumentListener(new DocumentListener() {
  public void changedUpdate(DocumentEvent e) { method(); } 
  public void removeUpdate(DocumentEvent e) { method(); }
  public void insertUpdate(DocumentEvent e) { method(); } 
};

My question is, I am repeating this code for all the 12 text fields, which I was not really happy. Is this the only way we have ? or can some one suggest me a better way ?

brimborium
  • 9,362
  • 9
  • 48
  • 76
Amarnath
  • 8,736
  • 10
  • 54
  • 81

1 Answers1

8
  • Switch from an anonymous class to an inner class and attach the same listener to each field. The source is contained in the event
  • Make it a separate class and keep on using separate listeners for each field. Avoids at least the code duplication

See this tutorial for an example of an inner class

Robin
  • 36,233
  • 5
  • 47
  • 99
  • +1 .. brilliant .. worked like a charm. No redundacy of code now .. Thanks a lot .. :) – Amarnath Oct 16 '12 at 09:11
  • 2
    You can still do this with an anonymous class: `DocumentListener listener = new DocumentListener() { ... }; for(JTextField textfield : fields) { textField.getDocument().addDocumentListener(listener); }` – Walter Laan Oct 16 '12 at 11:12
  • @WalterLaan Can you please post your answer separatly. It helps me to understand other ways of doing this. – Amarnath Oct 16 '12 at 11:30
  • Isn't this again an Inner Class as suggested by @WalterLaan in the comment, anonymous means without name that you cann't reference in future, IMHO. Do stand me corrected, if I am wrong. – nIcE cOw Oct 16 '12 at 15:50
  • @GagandeepBali no, that is an anonymous class as well. Only you assign it to a variable first so you can add it to multiple documents. – Robin Oct 16 '12 at 16:04
  • @Robin : Please have a look at this doc, what it has to say for [Anonymous Inner Classes](http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html) . What the idea in the comment is pointing to at, is the Local Inner Classes not Anonymous Classes. – nIcE cOw Oct 16 '12 at 16:33