Search code examples
javaswingjtreemouselistener

JTree : Check the level of selection


I am using MouseAdapter to check for double clicks on JTree nodes. I want to have some different action depending on the level of the node selected. How can I check the level of node ? Here is the code for the listener:

private MouseAdapter getMouseAdapter(JTree jtree) {
        final JTree tree = jtree;
        return new MouseAdapter() {

            @Override
            public void mousePressed(MouseEvent e) {
                TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
                if (selPath != null) {
                    if (e.getClickCount() == 2) {
                        String selectedNode = selPath.getLastPathComponent().toString();

              // >>>>>  check on which level of the tree this node is        
                    }
                }
            }};
    }

Solution

  • You can check the length of the path from selPath to the tree root by first calling the getPath() method of selPath and computing its length.

    Object[] array = selPath.getPath();
    int depth = array.length;