Add JPopup menu by right clicking on node in Swing in Java
In GUI,I am displaying one JTree
at the left hand side of JPanel
. Now for each Node(leaf)
, on Mouse right click I want to display JPopup
menu asking for displaying the statistics about Node
in right JPan开发者_运维百科el
.
As i am new to swing,Could any one help with code. Thanks in Advance.
Regards, Tushar Dodia.
Use JTree's method
public TreePath getPathForLocation(int x, int y)
Then TreePath
public Object getLastPathComponent()
That returns you desired node from point where user right clicked.
Seem to have caused a bit of confusion (confusing myself ;-) - so here's a code snippet for doing target location related configuration of the 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);
I took @kleopatra solution and changed it slightly. Maybe it isn't the best way but works for me.
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;
}
精彩评论