How can I wait to populate a JComboBox until the user presses the drop-down arrow?
Created May 4, 2012
John Zukowski You'll need to create a custom ComboBoxUI to deal with this. Override protected ComboPopup createPopup() and save a reference to the created BasicComboPopup. BasicComboPopup is a JPopupMenu so you can attach a PopupMenuListener to it. Then, adjust the model in popupMenuWillBecomeVisible. The following demonstrates this:
class MyComboBoxUI extends BasicComboBoxUI { public static ComponentUI createUI( JComponent c) { return new MyComboBoxUI(); } protected ComboPopup createPopup() { BasicComboPopup popup = (BasicComboPopup)super.createPopup(); PopupMenuListener listener = new PopupMenuListener() { public void popupMenuWillBecomeVisible( PopupMenuEvent e) { DefaultComboBoxModel model = (DefaultComboBoxModel)comboBox.getModel(); // change model here } public void popupMenuWillBecomeInvisible( PopupMenuEvent e) {} public void popupMenuCanceled( PopupMenuEvent e) {} }; popup.addPopupMenuListener(listener); return popup; } }