Java Swing How to - Handle JComboBox dropdown popup event








Question

We would like to know how to handle JComboBox dropdown popup event.

Answer

import java.awt.FlowLayout;
// ww w .j a  v  a  2 s.co m
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;

public class Main {

  public static void main(String[] args) {
    JComboBox c = new JComboBox();
    c.addPopupMenuListener(new PopupMenuListener() {

      @Override
      public void popupMenuCanceled(PopupMenuEvent e) {
        System.out.println(e.getSource());
      }

      @Override
      public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
        System.out.println(e.getSource());
      }

      @Override
      public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
        System.out.println(e.getSource());
      }
    });
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().setLayout(new FlowLayout());
    f.getContentPane().add(c);
    f.pack();
    f.setVisible(true);
  }
}