4

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've also tried using the 'isNodeChild()' method in MutableTreeNode instead of the getIndexOfChild() method on the TreeModel.

This seems like it should be a pretty trivial thing to do: Take a 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 the node as a child.

Suggestions?

4

1 回答 1

3

我认为代码很容易阅读。只需遍历每个并跟踪它是否是唯一的。如果您想跟踪它,如果添加它,它会返回 true/false

方法测试

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

方法:

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;
}
于 2013-07-29T14:59:09.997 回答