[英]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. 我需要在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);
}
}
but I added this component to 2 different dialogs. 但我将此组件添加到2个不同的对话框中。
The first one I can click and the selection is added to the JComboBox 我可以点击的第一个和选择添加到JComboBox
and the second, doing EXACTLY the same instantiation, and the same tests 第二,完全相同的实例化和相同的测试
The component has a different behaviour: 该组件具有不同的行为:
- The JPopupMenu disappears - JPopupMenu消失了
- 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
. 您可以在自定义ListCellRenderer
呈现树。 Alternatively, 或者,
I noticed that the JPopupMenu was loosing it's focus. 我注意到JPopupMenu正在失去它的焦点。
The solution was to add the component as the last component of the Panel. 解决方案是将组件添加为Panel的最后一个组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.