How do Display Custom PopupMenu in JComboBox

140 Views Asked by At

JComboBox displays a List on click. Instead of the list, I want to display a JPopupMenu. In the following code the event is triggered but the popup doesnt show up. Why?

JComboBox box = new JComboBox();

box.addPopupMenuListener(new PopupMenuListener() {
   @Override
   public void popupMenuWillBecomeVisible(PopupMenuEvent e) {      
     popupMenu.show(box, 0, box.getHeight());
   }
   ...
});
1

There are 1 best solutions below

0
hornisgrinde On

Alternatively one can use a mouseListener. Due to a JDK-bug https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4144505 one has to add the mouseListener to all Descendants like that:

 MouseAdapter comboPopupAdapter = new MouseAdapter() {
      @Override
      public void mousePressed(MouseEvent e) {
        popupMenu.show(box, 0, box.getHeight());
      }
    };
    box.addMouseListener(comboPopupAdapter);
    for (Component c : box.getComponents()) {
      c.addMouseListener(comboPopupAdapter);
    }