Question

I would like to find out how to get the name of the selected node in a JTree, not the userObject which is the text of the treenode.

I have manually created several tree nodes and I need to determine which one is selected by the node's name.

DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root"); 
DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("Hey it's node1!");
DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("Hey, it's node2!");
root.add(node1); root.add(node2); 

Now, based on that, I need to know if node1 or node2 is selected. I want a return value of node1 or node2 (variable name).

To make this more clear: I have a JFrame, with a JPanel, a JScrollPane, a JTree, and some text fields. Depending on which node is clicked (node 1, or node 2), I want to show or hide certain text fields.

Was it helpful?

Solution

If I wanted my Node to have a name, I'd extend the base class, here DefaultMutableTreeNode, and give it a String name field, and then fill that field with a value via a constructor, one that takes both a String name parameter and a String text parameter. And then also give it a getter method.

I wouldn't try to get its "variable" name since that is close to Meaningless. Many variables don't even have "names", that an object can be referenced by 2, 3, 100, ... variables.


Edit
You state in an edit:

To make this more clear: I have a JFrame, with a JPanel, a JScrollPane, a JTree, and some text fields. Depending on which node is clicked (node 1, or node 2), I want to show or hide certain text fields.

Again, variable names are close to meaningless and almost don't exist in compiled code. What counts are variable references -- being able to grab a variable, and object state -- the state of the fields held by that variable.

OTHER TIPS

Kind of old that thread, but in my opinion you do not have to derive any class. When you initialize a DefaultMutableTreeNode object with the optional parameter userObj, you can get this parameter again by calling getUserObject(). See the api for further information: https://docs.oracle.com/javase/10/docs/api/javax/swing/tree/DefaultMutableTreeNode.html

I think is is pretty much what you are searching for - at least I was searching for it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top