Close

Java Swing - JList with Text Field Filter Example

[Updated: Jul 4, 2018, Created: Nov 16, 2017]

This example shows how to use JTextField to filter JList items.

public class JListFilterExample {
  public static void main(String[] args) {
      List<Employee> employees = EmployeeDataAccess.getEmployees();
      DefaultListModel<Employee> model = new DefaultListModel<>();
      employees.forEach(model::addElement);
      JList<Employee> jList = new JList<>(model);
      jList.setCellRenderer(createListRenderer());
      JPanel panel = JListFilterDecorator.decorate(jList, JListFilterExample::employeeFilter);
      JFrame frame = createFrame();
      frame.add(panel);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
  }

  private static boolean employeeFilter(Employee emp, String str) {
      return emp.getName().toLowerCase().contains(str.toLowerCase());
  }

  private static ListCellRenderer<? super Employee> createListRenderer() {
      return new DefaultListCellRenderer() {
          private Color background = new Color(0, 100, 255, 15);
          private Color defaultBackground = (Color) UIManager.get("List.background");

          @Override
          public Component getListCellRendererComponent(JList<?> list, Object value, int index,
                                                        boolean isSelected, boolean cellHasFocus) {
              Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
              if (c instanceof JLabel) {
                  JLabel label = (JLabel) c;
                  Employee emp = (Employee) value;
                  label.setText(String.format("%s [%s]", emp.getName(), emp.getDept()));
                  if (!isSelected) {
                      label.setBackground(index % 2 == 0 ? background : defaultBackground);
                  }
              }
              return c;
          }
      };
  }

  private static JFrame createFrame() {
      JFrame frame = new JFrame("JList Example");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(new Dimension(600, 300));
      return frame;
  }
}
public class JListFilterDecorator {
  public static <T> JPanel decorate(JList<T> jList, BiPredicate<T, String> userFilter) {
      if (!(jList.getModel() instanceof DefaultListModel)) {
          throw new IllegalArgumentException("List model must be an instance of DefaultListModel");
      }
      DefaultListModel<T> model = (DefaultListModel<T>) jList.getModel();
      List<T> items = getItems(model);
      JTextField textField = new JTextField();
      textField.getDocument().addDocumentListener(new DocumentListener() {
          @Override
          public void insertUpdate(DocumentEvent e) {
              filter();
          }

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

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

          private void filter() {
              model.clear();
              String s = textField.getText();
              for (T item : items) {
                  if(userFilter.test(item, s)){
                      model.addElement(item);
                  }
              }
          }
      });

      JPanel panel = new JPanel(new BorderLayout());
      panel.add(textField, BorderLayout.NORTH);
      JScrollPane pane = new JScrollPane(jList);
      panel.add(pane);
      return panel;
  }

  private static <T> List<T> getItems(DefaultListModel<T> model) {
      List<T> list = new ArrayList<>();
      for (int i = 0; i < model.size(); i++) {
          list.add(model.elementAt(i));
      }
      return list;
  }
}
public class Employee {
  private String name;
  private String dept;
  private String phone;
  private String address;
    .............
}

Output

Example Project

Dependencies and Technologies Used:

  • datafactory 0.8: Library to generate data for testing.
  • JDK 1.8
  • Maven 3.3.9

JList with JText Field Filter Example Select All Download
  • list-text-filter
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • JListFilterDecorator.java

    See Also