Getting an event when a JComboBox is about to appear/disappear

Since JDK1.4, you can add PopupMenuListeners to your JComboBox. This allows you to get the events popupMenuWillBecomeVisible and popupMenuWillBecomeInvisible. Another event is supposed to be thrown, for a popupMenuCanceled, but is not, due to a bug.

Now that you have the possibility to get an event when the JComboBox popup is about to appear, you can lazily populate it. So only when the user wants to change the value of a JComboBox, you fill it up.

Here’s a short example. Due to a bug related to the order in which getPreferredSize and popupMenuWillBecomeVisible are called, the size of the component is not the desired size. Click twice on the JComboBox to see the desired size.

Main.java:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
 
      final JComboBox combobox = new JComboBox(new Object[] {"Default Item"});
      getContentPane().add(combobox);
 
      combobox.addPopupMenuListener(new PopupMenuListener() {
         public void popupMenuCanceled(PopupMenuEvent e) {
            System.out.println("popupMenu canceled");
         }
         public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
            System.out.println("popupMenu will become invisible");
         }
         public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
            if (combobox.getModel().getSize() <= 1) {
               // lazily populate combobox
               for (int i=0; i<100; i++) {
                  combobox.insertItemAt("Item #" + i, 0);
               }
               combobox.validate();
            }
            System.out.println("popupMenu will become visible");
         }
      });  
 
      setSize(300, 300);
   }
 
   public static void main(String[] args) {
      (new Main()).setVisible(true);
   }
}