I have a JTree with a few nodes and subnodes. When I click on a node I want to know on which depth is it (0, 1, 3). How can I know that?
selected_node.getDepth();
doesn't return the depth of current node..
I have a JTree with a few nodes and subnodes. When I click on a node I want to know on which depth is it (0, 1, 3). How can I know that?
selected_node.getDepth();
doesn't return the depth of current node..
You should be using getLevel
. getLevel
returns the number of levels above this node -- the distance from the root to this node. If this node is the root, returns 0. Alternatively, if for whatever reason you have obtained the Treenode[]
path (using getPath()
) then it is sufficient to take the length of that array.
getDepth
is different, as it returns the depth of the tree rooted at this node. Which is not what you want.
basicaly you have to Iterate
inside JTree
, but TreeSelectionListener
can returns interesting value, for example
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
public class TreeSelectionRow {
public TreeSelectionRow() {
JTree tree = new JTree();
TreeSelectionListener treeSelectionListener = new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent treeSelectionEvent) {
JTree treeSource = (JTree) treeSelectionEvent.getSource();
System.out.println("Min: " + treeSource.getMinSelectionRow());
System.out.println("Max: " + treeSource.getMaxSelectionRow());
System.out.println("Lead: " + treeSource.getLeadSelectionRow());
System.out.println("Row: " + treeSource.getSelectionRows()[0]);
}
};
tree.addTreeSelectionListener(treeSelectionListener);
String title = "JTree Sample";
JFrame frame = new JFrame(title);
frame.add(new JScrollPane(tree));
frame.setSize(300, 150);
frame.setVisible(true);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TreeSelectionRow treeSelectionRow = new TreeSelectionRow();
}
});
}
}
If you have a TreeSelectionListener
which handles the TreeSelectionEvent
, you can use the TreeSelectionEvent#getPaths
method to retrieve the selected TreePath
s. The TreePath#getPathCount
method returns the depth of the selected path.
You can also ask it directly to the JTree
(although you will need the listener to be informed when the selection changes) by using the JTree#getSelectionPaths
method.
© 2022 - 2024 — McMap. All rights reserved.