1

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..

Gabriel Câmara
  • 1,249
  • 15
  • 22

2 Answers2

2

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.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
1

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

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

Gabriel Câmara
  • 1,249
  • 15
  • 22