简体   繁体   中英

Custom JComboBox hiding JPopupMenu

I'm having a little headache with a situation. Maybe some of you have been through this before and can show me another way or even my error here.

I need to add a JTree inside a JComboBox and the code below works like a charm.

public class HierarchyComboBox extends JComboBox {
    HierarchyTree ht = new HierarchyTree();
    HierarchyComboBox box;
    JPopupMenu popup;
    MouseAdapter adapter = new MouseAdapter() { 
        @Override
        public void mouseClicked(MouseEvent arg0) {
            if (arg0.getClickCount() == 1) {
                removeAllItems();
                addItem(ht.getSelectedLevel());
//              ((JPopupMenu) comp).setVisible(false);
            }
        }
    };


    PopupMenuListener listener = new PopupMenuListener() {
        @Override
        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
            if (box == null) {
                box = (HierarchyComboBox) e.getSource();
                if (popup == null) {
                    final Object comp = box.getUI().getAccessibleChild(box, 0);
                    if (!(comp instanceof JPopupMenu))
                        return;
                    popup = (JPopupMenu) comp;
                }
                popup.removeAll();
                ht.getTreePane().setBorder(null);
                ht.getTreePane().setPreferredSize(new Dimension(box.getWidth(), 200));
                MyTree tree = (MyTree)ht.getTreePane().getViewport().getComponent(0);
                tree.addMouseListener(adapter);
                popup.add(ht.getTreePane());
            }
        }
        @Override
        public void popupMenuCanceled(PopupMenuEvent arg0) { }
        @Override
        public void popupMenuWillBecomeInvisible(PopupMenuEvent arg0) { }
    };

    public HierarchyComboBox() {
        setEditable(true);
        addPopupMenuListener(listener);
    }
}

but I added this component to 2 different dialogs.
The first one I can click and the selection is added to the JComboBox

and the second, doing EXACTLY the same instantiation, and the same tests

The component has a different behaviour:
- The JPopupMenu disappears
- It doesn't add the selection to the combo

Any ideas here?
Thanks in advance..

As shown in Providing a Custom Renderer , "A combo box uses a renderer to display each item in its menu." You could render the tree in a custom ListCellRenderer . Alternatively,

  • Render the tree in an adjacent component in response to an ActionListener .

  • Use a hierarchical model, shown here .

I noticed that the JPopupMenu was loosing it's focus.

The solution was to add the component as the last component of the Panel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM