Java Swing - Editable JComboBox Example

[Updated: Dec 12, 2017, Created: Dec 11, 2017]

An editable JCombo can be used for various purposes. In the following example, we will use it as a search component for JTable. Initially an empty combo box will be shown. The search text entered in it will be added to the combo model (only during runtime) for later uses.

public class EditableComboBoxExample {
  public static void main(String[] args) {
      //create a JTable
      JTable table = TableHelper.createTable();

      //create combo box as a search component
      JComboBox<String> searchComboBox = new JComboBox<>();
      searchComboBox.setEditable(true);
      searchComboBox.addActionListener(createSearchActionListener(searchComboBox, table));

      //wrap comboBox in a panel
      JPanel panel = new JPanel();
      panel.add(new JLabel("Search"));
      panel.add(searchComboBox);

      //frame
      JFrame frame = createFrame();
      frame.add(panel, BorderLayout.NORTH);
      frame.add(new JScrollPane(table));
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
  }

  private static ActionListener createSearchActionListener(JComboBox<String> comboBox, JTable table) {
      return e -> {
          if ("comboBoxChanged".equals(e.getActionCommand())) {
              String searchText = (String) comboBox.getSelectedItem();
              searchText = searchText.trim().toLowerCase();
              //if there are matches then add the search text in combo for later use
              if (TableHelper.searchInTable(table, searchText)) {
                  DefaultComboBoxModel<String> model = (DefaultComboBoxModel<String>) comboBox.getModel();
                  //check if search text is not empty and model already doesn't have it.
                  if (!searchText.isEmpty() && model.getIndexOf(searchText) == -1) {
                      model.addElement(searchText);
                  }
              }
          }
      };
  }

  private static JFrame createFrame() {
      JFrame frame = new JFrame("JComboBox Example");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(new Dimension(600, 500));
      return frame;
  }
}
public class TableHelper {

  public static JTable createTable() {
      //prepare columns
      Vector<String> columns = new Vector<>();
      columns.add("Name");
      columns.add("Dept");
      columns.add("Phone");
      columns.add("Address");

      //prepare rows
      Vector<Vector<String>> rows = new Vector();
      for (Employee employee : EmployeeDataAccess.getEmployees()) {
          Vector<String> row = new Vector<>();
          row.add(employee.getName());
          row.add(employee.getDept());
          row.add(employee.getPhone());
          row.add(employee.getAddress());
          rows.add(row);
      }
      return new JTable(rows, columns);
  }

  public static boolean searchInTable(JTable table, String searchText) {
      if (searchText == null) {
          return false;
      }
      int beforeFilterRowCount = table.getRowCount();
      RowSorter<? extends TableModel> rs = table.getRowSorter();
      if (rs == null) {
          table.setAutoCreateRowSorter(true);
          rs = table.getRowSorter();
      }
      TableRowSorter<? extends TableModel> rowSorter = (TableRowSorter<? extends TableModel>) rs;
      if (searchText.length() == 0) {
          rowSorter.setRowFilter(null);
      } else {
          rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + Pattern.quote(searchText)));
      }
      int afterFilterRowCount = table.getRowCount();
      return afterFilterRowCount!=0 && afterFilterRowCount != beforeFilterRowCount;
  }
}

Output

In above output the key pressed overlay is not a part of the example but a separate program (KeyPose) was used for that.

Example Project

Dependencies and Technologies Used :

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

Editable JCombBox Example Select All Download
  • editable-combo-box-example
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also