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
}
}
}};
}
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;
TreePath path = tree.getSelectionPath();
int level = path.getPathCount();
See the TreePath manual page .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.