Search code examples
javaswingjtablelistenerjtextfield

Is it possible to have a single document listener to multiple text fields in Swing


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 ?


Solution

    • 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