在图形用户界面中,我在JPanel的左侧显示了一个JTree。现在,对于每个Node(leaf),在鼠标右键单击时,我想显示JPopup菜单,要求在右JPanel中显示有关Node的统计信息。
由于我是swing的新手,有人可以帮助我编写代码吗?提前谢谢。
你好,图沙尔·多迪亚。
发布于 2011-06-22 15:31:59
使用JTree的方法
public TreePath getPathForLocation(int x, int y)然后是TreePath
public Object getLastPathComponent()这将从用户右键单击的位置返回所需的节点。
发布于 2011-06-23 16:25:50
似乎引起了一些困惑(把我自己搞糊涂了;-) -这里有一段代码片段,用于对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);发布于 2012-12-14 05:24:46
我采用了@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;
}https://stackoverflow.com/questions/6436287
复制相似问题