Handle item selected or deselected event in the JComboBox - Java Swing

Java examples for Swing:JComboBox

Introduction

An item listener is notified whenever an item is selected or deselected.

import java.awt.event.ItemEvent;

import javax.swing.JComboBox;

public class Main {

  public static void main(String[] args) {
    String[] sList = new String[] { "Spring", "Summer", "Fall", "Winter" };
    JComboBox<String> seasons = new JComboBox<>(sList);

    seasons.addItemListener((ItemEvent e) -> {
      Object item = e.getItem();
      if (e.getStateChange() == ItemEvent.SELECTED) {
        System.out.println(item + " has been selected");
      } else if (e.getStateChange() == ItemEvent.DESELECTED) {
        System.out.println(item + " has been deselected");
      }
    });
  }
}

Related Tutorials