1

我有点头疼的情况。也许你们中的一些人以前经历过这种情况,并且可以在这里向我展示另一种方式,甚至是我的错误。

我需要在 JComboBox 中添加一个 JTree,下面的代码就像一个魅力。

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);
    }
}

但我将此组件添加到 2 个不同的对话框中。
我可以单击的第一个并将选择添加到 JComboBox

第二,完全相同的实例化和相同的测试

组件具有不同的行为:
- JPopupMenu 消失
- 它不会将选择添加到组合中

这里有什么想法吗?
提前致谢..

4

2 回答 2

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.

于 2013-07-04T14:23:01.260 回答
1

我注意到 JPopupMenu 失去了焦点。

解决方案是将组件添加为面板的最后一个组件。

于 2013-07-04T14:53:42.007 回答