How can I wait to populate a JComboBox until the user presses the drop-down arrow?

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;
  }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact