hello there,
i have a JTree which gets populated from the db.the structure of my Jtree is like this
-c
-d
-f
-g
now i want to have a popupmenu for each of those nodes.i mean i want to have different popup menu for each nodes.for example the parent node c will have "add c","delete c","edit c" node d will have "add d","delete d","edit d" and so on.
i tried to use
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
selectedNode.getLevel()
but this does not work when i right click on the nodes.i get this error java.lang.NullPointerException.but if i left click it first then right clcik it sjows me the level.
also i want to know how do i implement my code so the i get different pop menu according to the nodes i right clcik.
my code below shows the same popup menu for anywhere i click on my jtree
//constr
treePopupMenu = createPopupMenuDslam();
public void mouseReleased(MouseEvent me)
{
if (me.isPopupTrigger())
{
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
treePopupMenu.show(me.getComponent(), me.getX(), me.getY());
System.out.println(selectedNode.getLevel());
}
}
});
private JPopupMenu createPopupMenuDslam()
{
final JPopupMenu pm = new JPopupMenu();
JMenuItem addItem = new JMenuItem(" Add ");
addItem.setActionCommand("add");
addItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JOptionPane.showConfirmDialog(pm, "Was pressed popup menu ADD item");
}
});
pm.add(addItem);
JMenuItem editItem = new JMenuItem(" Edit ");
editItem.setActionCommand("edit");
editItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JOptionPane.showConfirmDialog(pm, "Was pressed popup menu EDIT item");
}
});
pm.add(editItem);
pm.add(new JSeparator());
JMenuItem deleteItem = new JMenuItem(" Delete ");
deleteItem.setActionCommand("delete");
deleteItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JOptionPane.showConfirmDialog(pm, "Was pressed popup menu DELETE item");
}
});
pm.add(deleteItem);
return pm;
}
cheers
zolf
you need to eaith:
first select the node
or don't use getLastSelectedPathCompone
you can get the path using:
TreePath selPath = tree.getPathForLocation(me