How to get node current depth in JTree?

I have a JTree with several nodes and trays. When I click on node, I want to know at what depth it is (0, 1, 3). How can I know this?

selected_node.getDepth(); 

does not return current depth node ..

+6
source share
3 answers

You must use 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 some reason you got the path Treenode[] (using getPath() ), then just take the length of this array.

getDepth is different because it returns the depth of the tree root in this node. This is not what you want.

+8
source

Basically you should Iterate inside JTree , but TreeSelectionListener can return an interesting value, like

 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(); } }); } } 
+3
source

If you have a TreeSelectionListener that processes a TreeSelectionEvent , you can use the TreeSelectionEvent#getPaths to retrieve the selected TreePath s. The TreePath#getPathCount returns the depth of the selected path.

You can also request it directly in JTree (although you need the listener to be informed when the selection changes) using JTree#getSelectionPaths .

+2
source

Source: https://habr.com/ru/post/912846/


All Articles