Java Swing - JComboBox with ListCellRenderer, ItemListener and ActionListener Example

[Updated: Nov 20, 2017, Created: Nov 20, 2017]

Following example shows basic use of JCombo with a custom renderer and with listeners (ItemListener and ActionListener).

public class JComboBoxExample {
  public static void main(String[] args) {
      List<Employee> employees = EmployeeDataAccess.getEmployees();
      JComboBox<Employee> comboBox = new JComboBox<>(employees.toArray(new Employee[employees.size()]));
      //renderer
      comboBox.setRenderer(createListRenderer());
      //listeners
      comboBox.addItemListener(createItemListener());
      comboBox.addActionListener(createActionListener());
      //wrap in a panel
      JPanel panel = new JPanel();
      panel.add(comboBox);
      //frame
      JFrame frame = createFrame();
      frame.add(panel);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
  }

  private static ActionListener createActionListener() {
      return e -> {
          JComboBox<Employee> comboBox = (JComboBox<Employee>) e.getSource();
          System.out.println("ActionPerformed: " + comboBox.getSelectedItem());
      };
  }

  private static ItemListener createItemListener() {
      return e -> {
          if (e.getStateChange() == ItemEvent.SELECTED) {
              System.out.println("Selected: " + e.getItem());
          } else if (e.getStateChange() == ItemEvent.DESELECTED) {
              System.out.println("DeSelected: " + e.getItem());
          } else {
              System.out.println("Other StateChange: " + e.getStateChange());
          }
      };
  }

  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) {
              super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

              Employee emp = (Employee) value;
              this.setText(String.format("%s [%s]", emp.getName(), emp.getDept()));
              if (!isSelected) {
                  this.setBackground(index % 2 == 0 ? background : defaultBackground);
              }
              return this;
          }
      };
  }

  private static JFrame createFrame() {
      JFrame frame = new JFrame("JComboBox Example");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(new Dimension(600, 300));
      return frame;
  }
}
public class Employee {
  private String name;
  private String dept;
  private String phone;
  private String address;
    .............
}

Output

On item selection following is printed on console window:

DeSelected: Employee{name='Lindsey Craft', dept='Account', phone='434-297-2813', address='1110 Harlan Court, Stillmore'}
Selected: Employee{name='Jeffrey Suarez', dept='Admin', phone='058-795-5965', address='917 Hedgewood Square, Bowens Mill'}
ActionPerformed: Employee{name='Jeffrey Suarez', dept='Admin', phone='058-795-5965', address='917 Hedgewood Square, Bowens Mill'}

Example Project

Dependencies and Technologies Used :

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

JCombBox with Renderer and Listeners Example Select All Download
  • combo-box-example
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also