import javax.swing.JTextField; import javax.swing.RowFilter; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; public class TableSearchDocumentListener implements DocumentListener { private final JTextField searchTextField; private final TableRowSorter tableRowSorter; public TableSearchDocumentListener(JTextField searchTextField, TableRowSorter tableRowSorter) { this.searchTextField = searchTextField; this.tableRowSorter = tableRowSorter; } @Override public void insertUpdate(DocumentEvent e) { updateTableRowSorter(); } @Override public void removeUpdate(DocumentEvent e) { updateTableRowSorter(); } @Override public void changedUpdate(DocumentEvent e) { updateTableRowSorter(); } private void updateTableRowSorter() { String searchFieldText = searchTextField.getText(); if (searchFieldText != null) { String[] keywords = searchFieldText.split(" "); tableRowSorter.setRowFilter(new KeywordFilter(keywords)); } } public class KeywordFilter extends RowFilter { private final String[] keywords; // Constructor for filtering a single keyword public KeywordFilter(String keyword) { this.keywords = new String[1]; this.keywords[0] = keyword.toLowerCase(); } // Constructor for filtering an array of keywords // Only the rows that contain every keyword are displayed public KeywordFilter(String[] keywords) { this.keywords = keywords; // convert all keywords to lower case for (int i = 0; i < keywords.length; i++) { keywords[i] = keywords[i].toLowerCase(); } } @Override public boolean include(RowFilter.Entry entry) { // Does the row contain all keywords? Assume true and set to false if // one is missing boolean containsAll = true; for (int i = 0; containsAll == true && i < keywords.length; i++) { // Is the keyword contained in one of the columns? Assume false and // set to true if it is found boolean containsThis = false; for (int j = 0; containsThis == false && j < entry.getValueCount(); j++) { if (entry.getStringValue(j).toLowerCase().contains(keywords[i])) { containsThis = true; } } if (!containsThis) { containsAll = false; } } return containsAll; } } }