在GUI中,我在JTree
的左侧显示一个JPanel
。现在每个Node(leaf)
,鼠标右键单击我想显示JPopup
菜单,要求在右Node
中显示JPanel
的统计信息。
由于我是新手,我可以帮助代码。 在此先感谢。
此致 Tushar Dodia。
答案 0 :(得分:3)
使用JTree的方法
public TreePath getPathForLocation(int x, int y)
然后是TreePath
public Object getLastPathComponent()
从用户右键单击的点返回所需节点。
答案 1 :(得分:3)
似乎引起了一些混乱(混淆了我自己;-) - 所以这里是一个代码片段,用于执行componentPopup的目标位置相关配置
JPopupMenu popup = new JPopupMenu();
final Action action = new AbstractAction("empty") {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
};
popup.add(action);
JTree tree = new JTree() {
/**
* @inherited <p>
*/
@Override
public Point getPopupLocation(MouseEvent e) {
if (e != null) {
TreePath path = getClosestPathForLocation(e.getX(), e.getY());
action.putValue(Action.NAME, String.valueOf(path.getLastPathComponent()));
return e.getPoint();
}
action.putValue(Action.NAME, "no mouse");
return null;
}
};
tree.setComponentPopupMenu(popup);
答案 2 :(得分:0)
我拿了@kleopatra解决方案并稍微改了一下。 也许这不是最好的方式,但对我有用。
JTree tree = new JTree() {
private static final long serialVersionUID = 1L;
@Override public Point getPopupLocation(MouseEvent e) {
if (e == null) return new Point(0,0);
TreePath path = getClosestPathForLocation(e.getX(), e.getY());
Object selected = path != null ? path.getLastPathComponent() : null;
setComponentPopupMenu(getMenuForTreeNode(getComponentPopupMenu(), selected));
setSelectionPath(path);
return e.getPoint();
}
};
public JPopupMenu getMenuForTreeNode(JPopupMenu menu, Object treeNode) {
if (menu == null) menu = new JPopupMenu("Menu:");
menu.removeAll();
if (treeNode instanceof MyTreeItem) {
menu.add(new JMenuItem("This is my tree item: " + treeNode.toString()));
}
return menu;
}