Link to home
Start Free TrialLog in
Avatar of rzvika3
rzvika3

asked on

get data from JTree after clicking on a node

as you all know, i have a JTree.
i want that each time i click on a node in the tree, i could get data from it. what method should i use and how can i get a reference to the tree node: Object ?
thank you.
Avatar of martinag
martinag

tree.addTreeSelectionListener(new TreeSelectionListener() {
  public void valueChanged(TreeSelectionEvent e) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode)e.getPath().getLastPathComponent();
    Object o = node.getUserObject();
    ...
  }
});

Martin
This doesn't listen for clicks, actually it listens for selections. That happens when you click on another node than the one having focus or select using the arrow keys.

Martin
ASKER CERTIFIED SOLUTION
Avatar of diakov
diakov

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of rzvika3

ASKER

ok, thank you both.
diakov, i see that in the code i can seperate between one click and two cliks. is there a way to know if it is right click (my final purpose is to popup a menue when right click on a node and in the menu wil be lets say "delete" and Add". if you can write the code to how adding rightclick listener(or something like that) and how i can know what the user pressed on (delete or add) please write. i will erase to 100 points.
thank you again!

I believe

((e.getModifiers() & e.BUTTON3_MASK) > 0)

will return true if the right button has been pressed.

In similar way you can check for CTRL button down while mouse clicking and etc.

Cheers,
  Nik
Avatar of rzvika3

ASKER

diakov, you didn't mentioned this part:
(my final purpose is to popup a menue when right click on a node and in the menu wil be lets say "delete" and Add". if you can write the code to how adding rightclick listener(or something like that) and how i can know what the user pressed on (delete or add) please write.

This is what I did.
I defined a

//I believe you can use some other pannel
rmenu = new symantec.itools.awt.BorderPanel();
rmenu.setBounds(0,0,68,40);
rmenu.setBackground(new Color(12632256));
//and then added several labels in it.
.
//this is the mouse listener for the menu
rmenu.addMouseListener(rmenu_listener);

//Then in the mouse listener of the tree:

if (modif == event.BUTTON3_MASK)
{
  Rectangle r = rmenu.getBounds();
  r.x = event.getX();
  r.y = event.getY();
  r.height = 68;
  rmenu.setBounds(r);
  rmenu.setVisible(true);
  rmenu.setEnabled(true);
}

in the listener for the menu you have to track how the mouse moves and change the color of the labels for example.

And there you go, you have a right click menu.

Cheers,
  Nik
Avatar of rzvika3

ASKER

Adjusted points to 100