Is there a way to ensure that nodes in JTree are unique, preferably without writing a TreeModel implementation?

I'm currently trying

DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot(); DefaultMutableTreeNode child = new DefaultMutableTreeNode("String"); if (model.getIndexOfChild(root, child) == -1) { model.insertNodeInto(child, root, root.getChildCount()); } model.reload(root); 

I also tried using the 'isNodeChild () method in MutableTreeNode instead of the getIndexOfChild() method on TreeModel.

This seems to be a pretty trivial task: take the given node in the tree and see if there is a child node with the specified value (in this case a String ) that already exists. If there is, do not add a new child node. Otherwise, add node as a child.

Suggestions?

+4
source share
1 answer

I think the code is pretty easy to read. Just iterate over each and track if it is unique. If you want to track it, it returns true / false if it was added

Method testing

 DefaultMutableTreeNode child = new DefaultMutableTreeNode("String"); DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("String"); DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("String1"); addUniqueNode(child, model); // Will get added addUniqueNode(child1, model); // Will not get added addUniqueNode(child2, model); // Will get added 

Method:

 public boolean addUniqueNode(DefaultMutableTreeNode childNode, DefaultTreeModel model) { DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot(); // Check each node boolean isUnique = true; for (int i = 0; i < model.getChildCount(root); i++) { Object compUserObj = ((DefaultMutableTreeNode) model.getChild(root, i)).getUserObject(); if (compUserObj.equals(childNode.getUserObject())) { isUnique = false; break; } } // If Unique, insert if(isUnique) model.insertNodeInto(childNode, root, root.getChildCount()); return isUnique; } 
+3
source

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


All Articles