我正在尝试在 Java JTree 中实现弹出菜单。我将 DefaultTreeCellRenderer (以更改节点外观)和 DefaultTreeCellEditor (以创建组件以将事件侦听器附加到,因为显然 DefaultTreeCellRenderer.getTreeCellRendererComponent() 返回的组件不能做到这一点?)。我真的不想“编辑”节点,只是能够在节点被右键单击时弹出一个菜单,但这是我现在能想到的唯一方法......
下面是我到目前为止的代码——我只是想弄清楚如何捕获 MouseEvents。它有点工作,但很糟糕。有什么更好的方法来完成我在这里尝试做的事情?
private class My_TreeCellRenderer extends DefaultTreeCellRenderer {
My_TreeCellRenderer() {
super ();
}
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
// set label text and tool tips
setText(((My_Object)value).getTreeLabel());
setToolTipText(((My_Object)value).getTreeToolTip());
return this;
}
}
private class My_TreeCellEditor extends DefaultTreeCellEditor {
private MouseAdapter ma;
My_TreeCellEditor(JTree tree, DefaultTreeCellRenderer renderer) {
super (tree, renderer);
ma = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
System.out.println("My Popup");
}
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
System.out.println("My Popup");
}
}
};
}
public Component getTreeCellEditorComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row) {
String src_filename = null;
// return non-editing component
Component c = renderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, true);
// add mouse listener if it's not listening already
MouseListener mouseListeners[] = c.getMouseListeners();
int i;
for (i=0; i < mouseListeners.length && mouseListeners[i] != ma; i++);
if (i >= mouseListeners.length)
c.addMouseListener(ma);
return c;
}
protected boolean canEditImmediately(EventObject event) {
if (event instanceof MouseEvent && ((MouseEvent)event).getClickCount() == 1)
return true;
else
return false;
}
}