Java Code Examples for javax.swing.tree.DefaultMutableTreeNode#children()

The following examples show how to use javax.swing.tree.DefaultMutableTreeNode#children() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PreorderWalker.java    From jlibs with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args){
    Class<Number> c1 = Number.class;
    Class<Integer> c2 = Integer.class;
    System.out.println(c1.isAssignableFrom(c2));
    System.out.println(c1.isAssignableFrom(c2));

    JFrame frame = new JFrame();
    JTree tree = new JTree();
    frame.getContentPane().add(new JScrollPane(tree));
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

    final PreorderWalker<DefaultMutableTreeNode> seq = new PreorderWalker<DefaultMutableTreeNode>((DefaultMutableTreeNode)tree.getModel().getRoot(), new Navigator<DefaultMutableTreeNode>(){
        @Override
        @SuppressWarnings({"unchecked"})
        public Sequence<DefaultMutableTreeNode> children(DefaultMutableTreeNode elem){
            return new EnumeratedSequence<DefaultMutableTreeNode>(elem.children());
        }
    });
    WalkerUtil.print(seq, null);
}
 
Example 2
Source File: TreeUtil.java    From Zettelkasten with GNU General Public License v3.0 6 votes vote down vote up
private static void expandAllTrees(TreePath parent, JTree tree) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) parent.getLastPathComponent();
    if (node.getChildCount() >= 0) {
        for (Enumeration e = node.children(); e.hasMoreElements();) {
            DefaultMutableTreeNode n = (DefaultMutableTreeNode) e.nextElement();
            TreePath path = parent.pathByAddingChild(n);
            expandAllTrees(path, tree);
        }
    }
    // retrieve treenode user object
    TreeUserObject userObject = (TreeUserObject) node.getUserObject();
    // check whether deepest level is reached.
    if ((expandLevel != -1 && node.getLevel() < expandLevel) || -1 == expandLevel) {
        // check whether treenode-id is in the list of collapsed items
        if (userObject != null && collapsedNodes.contains(userObject.getId())) {
            // if yes, collapse treenode
            tree.collapsePath(parent);
        } else {
            // else expand it
            tree.expandPath(parent);
        }
    } else {
        tree.collapsePath(parent);
    }
}
 
Example 3
Source File: ModelTreeRTStats.java    From mts with GNU General Public License v3.0 6 votes vote down vote up
synchronized public DefaultMutableTreeNode getNode(DefaultMutableTreeNode nodeChild, DefaultMutableTreeNode nodeParent) {
    // Initialisation of the node returned
    DefaultMutableTreeNode node = null;

    // We get all children of node parent
    Enumeration<DefaultMutableTreeNode> allChildren = (Enumeration<DefaultMutableTreeNode>)(Object)nodeParent.children();

    // For each child
    while (allChildren.hasMoreElements()) {
        // Get the current child
        node = allChildren.nextElement();

        // If this child match (with the name) with the node searching
        if (node.toString().equals(nodeChild.toString())) {
            // We return the node
            return node;
        }
    }

    // Else (that's mean we don't found) we return the new node child
    node = nodeChild;
    return node;
}
 
Example 4
Source File: ProjectTreeBuilder.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void updateNodesContaining(@Nonnull Collection<VirtualFile> filesToRefresh, @Nonnull DefaultMutableTreeNode rootNode) {
  if (!(rootNode.getUserObject() instanceof ProjectViewNode)) return;
  ProjectViewNode node = (ProjectViewNode)rootNode.getUserObject();
  Collection<VirtualFile> containingFiles = null;
  for (VirtualFile virtualFile : filesToRefresh) {
    if (!virtualFile.isValid()) {
      addSubtreeToUpdate(rootNode); // file must be deleted
      return;
    }
    if (node.contains(virtualFile)) {
      if (containingFiles == null) containingFiles = new SmartList<>();
      containingFiles.add(virtualFile);
    }
  }
  if (containingFiles != null) {
    updateNode(rootNode);
    Enumeration children = rootNode.children();
    while (children.hasMoreElements()) {
      DefaultMutableTreeNode child = (DefaultMutableTreeNode)children.nextElement();
      updateNodesContaining(containingFiles, child);
    }
  }
}
 
Example 5
Source File: CodeEditor.java    From CQL with GNU Affero General Public License v3.0 6 votes vote down vote up
private TreePath conv(TreePath path) {
	TreePath parent = path.getParentPath();
	if (parent == null) {
		return new TreePath(tree.getModel().getRoot());
	}
	TreePath rest = conv(parent);
	DefaultMutableTreeNode last = (DefaultMutableTreeNode) rest.getLastPathComponent();
	DefaultMutableTreeNode us = (DefaultMutableTreeNode) path.getLastPathComponent();
	Enumeration<TreeNode> cs = last.children();
	if (cs == null) {
		return null;
	}
	while (cs.hasMoreElements()) {
		DefaultMutableTreeNode m = (DefaultMutableTreeNode) cs.nextElement();
		if (nodeEq(m, us)) {
			return rest.pathByAddingChild(m);
		}
	}
	return null;
}
 
Example 6
Source File: CamoChoiceDialog.java    From megamek with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This recursive method is a hack: DirectoryItems flattens the directory
 * structure, but it provides useful functionality, so this method will
 * reconstruct the directory structure for the JTree.
 *
 * @param node
 * @param names
 */
private void addCategoryToTree(DefaultMutableTreeNode node, String[] names) {

    // Shouldn't happen
    if (names.length == 0) {
        return;
    }

    boolean matched = false;
    for (Enumeration<?> e = node.children(); e.hasMoreElements();) {
        DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) e.nextElement();
        String nodeName = (String) childNode.getUserObject();
        if (nodeName.equals(names[0])) {
            if (names.length > 1) {
                addCategoryToTree(childNode,
                        Arrays.copyOfRange(names, 1, names.length));
                matched = true;
            } else {
                // I guess we're done? This shouldn't happen, as there
                // shouldn't be duplicates
            }
        }
    }

    // If we didn't match, lets create nodes for each name
    if (!matched) {
        DefaultMutableTreeNode root = node;
        for (int i = 0; i < names.length; i++) {
            DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(
                    names[i]);
            root.add(newNode);
            root = newNode;
        }
    }
}
 
Example 7
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
private void updateParentUserObject(DefaultMutableTreeNode parent) {
  FilterableNode uo = (FilterableNode) parent.getUserObject();
  // Java 9: Enumeration<TreeNode> children = parent.children();
  Enumeration<?> children = parent.children();
  while (children.hasMoreElements()) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) children.nextElement();
    FilterableNode check = (FilterableNode) node.getUserObject();
    if (check.status) {
      uo.status = true;
      return;
    }
  }
  uo.status = false;
}
 
Example 8
Source File: Viewer.java    From accumulo-examples with Apache License 2.0 5 votes vote down vote up
@Override
public void treeCollapsed(TreeExpansionEvent event) {
  DefaultMutableTreeNode node = (DefaultMutableTreeNode) event.getPath().getLastPathComponent();
  @SuppressWarnings("unchecked")
  Enumeration<DefaultMutableTreeNode> children = node.children();
  while (children.hasMoreElements()) {
    DefaultMutableTreeNode child = children.nextElement();
    log.debug("removing children of " + ((NodeInfo) child.getUserObject()).getFullName());
    child.removeAllChildren();
  }
}
 
Example 9
Source File: Model.java    From Luyten with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public DefaultMutableTreeNode getChild(DefaultMutableTreeNode node, TreeNodeUserObject name) {
	Enumeration<DefaultMutableTreeNode> entry = node.children();
	while (entry.hasMoreElements()) {
		DefaultMutableTreeNode nods = entry.nextElement();
		if (((TreeNodeUserObject) nods.getUserObject()).getOriginalName().equals(name.getOriginalName())) {
			return nods;
		}
	}
	return null;
}
 
Example 10
Source File: FilterTreeModel.java    From swing_library with MIT License 5 votes vote down vote up
/**
 * Clone/Copy a tree node. TreeNodes in Swing don't support deep cloning.
 * 
 * @param orig to be cloned
 * @return cloned copy
 */
private DefaultMutableTreeNode copyNode(final DefaultMutableTreeNode orig) {
	if (orig == null)
		return null;
	DefaultMutableTreeNode newOne = new DefaultMutableTreeNode();
	newOne.setUserObject(orig.getUserObject());
	newOne.setAllowsChildren(!orig.isLeaf());

	Enumeration<DefaultMutableTreeNode> enm = orig.children();
	while (enm.hasMoreElements()) {
		DefaultMutableTreeNode child = enm.nextElement();
		newOne.add(copyNode(child));
	}
	return newOne;
}
 
Example 11
Source File: HelpModuleCollection.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void addPrebuiltItem(DefaultMutableTreeNode tn, Path tocPath,
		Map<String, TOCItemExternal> mapByDisplay) {

	Object userObject = tn.getUserObject();
	CustomTreeItemDecorator item = (CustomTreeItemDecorator) userObject;
	if (item != null) {
		DefaultMutableTreeNode parent = (DefaultMutableTreeNode) tn.getParent();
		TOCItemExternal parentItem = null;
		if (parent != null) {
			CustomTreeItemDecorator dec = (CustomTreeItemDecorator) parent.getUserObject();
			if (dec != null) {
				parentItem = mapByDisplay.get(dec.getDisplayText());
			}
		}

		ID targetID = item.getID();

		String displayText = item.getDisplayText();
		String tocID = item.getTocID();
		String target = targetID == null ? null : targetID.getIDString();
		TOCItemExternal external = new TOCItemExternal(parentItem, tocPath, tocID, displayText,
			target, item.getName(), -1);
		mapByDisplay.put(displayText, external);
	}

	@SuppressWarnings("rawtypes")
	Enumeration children = tn.children();
	while (children.hasMoreElements()) {
		DefaultMutableTreeNode child = (DefaultMutableTreeNode) children.nextElement();
		addPrebuiltItem(child, tocPath, mapByDisplay);
	}
}
 
Example 12
Source File: AnalyzeSizeToolWindow.java    From size-analyzer with Apache License 2.0 5 votes vote down vote up
private void showCategoryInCategoryPanelFor(DefaultMutableTreeNode categoryNode) {
  CategoryData category = (CategoryData) categoryNode.getUserObject();
  categoryTitle.clear();
  categoryTitle.append(category.toString(), SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES);
  if (category.totalSizeSaved() != null) {
    categoryTitle.append(
        "  Estimated savings: " + category.totalSizeSaved(),
        SimpleTextAttributes.GRAYED_ATTRIBUTES);
  }
  categoryTitle.setMaximumSize(categoryTitle.getPreferredSize());

  suggestionsPanel.removeAll();
  for (Enumeration<?> nodeEnumeration = categoryNode.children();
      nodeEnumeration.hasMoreElements(); ) {
    Object nodeValue = nodeEnumeration.nextElement();
    if (nodeValue instanceof DefaultMutableTreeNode) {
      DefaultMutableTreeNode node = (DefaultMutableTreeNode) nodeValue;
      String linkTitle = extractLinkTitle(node);
      suggestionsPanel.add(
          new LinkLabel<>(
              linkTitle,
              null,
              new LinkListener<Object>() {
                @Override
                @SuppressWarnings("rawtypes") // Declaration uses raw type, needed for override.
                public void linkSelected(LinkLabel source, Object linkData) {
                  suggestionTree.clearSelection();
                  TreePath selectedNode =
                      new TreePath(((DefaultMutableTreeNode) linkData).getPath());
                  suggestionTree.addSelectionPath(selectedNode);
                  suggestionTree.scrollPathToVisible(selectedNode);
                }
              },
              node));
    }
  }
}
 
Example 13
Source File: TreeImporter.java    From IrScrutinizer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void treeExpanded(TreeExpansionEvent event) {
    DefaultMutableTreeNode remote = (DefaultMutableTreeNode) event.getPath().getLastPathComponent();
    if (!Remote.class.isInstance(remote.getUserObject())) // Just to be on the safe side...
        return;

    for (Enumeration e = remote.children(); e.hasMoreElements();) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement();
        Command command = (Command) node.getUserObject();
    }
}
 
Example 14
Source File: FilterOpUI.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private static DefaultMutableTreeNode findItem(DefaultMutableTreeNode parentItem, String filterName) {
    if (!parentItem.isLeaf()) {
        final Enumeration enumeration = parentItem.children();
        while (enumeration.hasMoreElements()) {
            final DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) enumeration.nextElement();
            final DefaultMutableTreeNode found = findItem(treeNode, filterName);
            if (found != null)
                return found;
        }
    }

    if (parentItem.toString().equals(filterName))
        return parentItem;
    return null;
}
 
Example 15
Source File: RedisFragmentedKeyTreeModel.java    From nosql4idea with Apache License 2.0 5 votes vote down vote up
private static void addChildren(DefaultMutableTreeNode parentNode, DefaultMutableTreeNode originalChildNode) {
    Enumeration children = originalChildNode.children();
    while (children.hasMoreElements()) {
        DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) children.nextElement();
        parentNode.add((MutableTreeNode) childNode.clone());
    }
}
 
Example 16
Source File: TreeTabbedPanel.java    From jd-gui with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected DefaultMutableTreeNode searchTreeNode(URI uri, DefaultMutableTreeNode node) {
    if (node instanceof TreeNodeExpandable) {
        ((TreeNodeExpandable)node).populateTreeNode(api);
    }

    String u = uri.toString();
    T child = null;
    Enumeration enumeration = node.children();

    while (enumeration.hasMoreElements()) {
        T element = (T)enumeration.nextElement();
        String childU = element.getUri().toString();

        if (u.length() > childU.length()) {
            if (u.startsWith(childU)) {
                char c = u.charAt(childU.length());
                if ((c == '/') || (c == '!')) {
                    child = element;
                    break;
                }
            }
        } else if (u.equals(childU)) {
            child = element;
            break;
        }
    }

    if (child != null) {
        if (u.equals(child.getUri().toString())) {
            return child;
        } else {
            // Parent tree node found -> Recursive call
            return searchTreeNode(uri, child);
        }
    } else {
        // Not found
        return null;
    }
}
 
Example 17
Source File: ModelTreeRTStats.java    From mts with GNU General Public License v3.0 4 votes vote down vote up
synchronized public void insertNode(DefaultMutableTreeNode nodeChild, DefaultMutableTreeNode nodeParent, int position) {
    // Flag for know if the nodeChild already exist in the nodeParent
    boolean alreadyExist = false;

    // We get all children of node parent
    Enumeration<DefaultMutableTreeNode> allChildren = (Enumeration<DefaultMutableTreeNode>)(Object)nodeParent.children();

    // For each child
    while (allChildren.hasMoreElements()) {
        // If this child match (with the name) with the node searching
        if (allChildren.nextElement().toString().equals(nodeChild.toString())) {
            // That's mean the node already exist
            alreadyExist = true;
        }
    }

    // If the node don't exist
    if (!alreadyExist) {
        // We really insert the node in the tree in the good position
        insertNodeInto(nodeChild, nodeParent, position);

        // Code for expand only this new node

        // We get the path of the child
        TreeNode[] childTreeNode = nodeChild.getPath();

        // We prepare a new TreeNode tab for the path of the parent (=the child path without the last element)
        TreeNode[] parentTreeNode = new TreeNode[childTreeNode.length - 1];

        // If tree is ready
        if (sectionIsCreate) {
            // Increment variable to progress in parent path
            int i = 0;

            // For each element of childTreeNode
            for (TreeNode currentNode : childTreeNode) {
                // if we are not on the last element
                if (i < childTreeNode.length - 1) {
                    // parentTreeNode received the currentNode for the child path
                    parentTreeNode[i] = currentNode;
                }
                // Increment i
                i++;
            }
        }
    }
    // Else we not insert again the node
}
 
Example 18
Source File: TemplatesUI.java    From CodeGen with MIT License 4 votes vote down vote up
@Override
public boolean isModified(){
    Templates templates = settingManager.getTemplates();
    DefaultMutableTreeNode topNode = (DefaultMutableTreeNode) templateTree.getModel().getRoot();
    // 获取映射map
    Map<String, List<CodeGroup>> groupsMap = templates.getGroupsMap();
    Map<String, List<CodeTemplate>> templateMap = templates.getTemplatesMap();

    // root的判断, 数量判断, name?
    List<CodeRoot> roots = templates.getRoots();
    if(topNode.getChildCount() != roots.size()){
        return true;
    }
    Enumeration rootEnum = topNode.children();
    while (rootEnum.hasMoreElements()) {
        // 组的判断, 数量判断
        DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) rootEnum.nextElement();
        CodeRoot root = (CodeRoot) rootNode.getUserObject();
        if (rootNode.getChildCount() != groupsMap.get(root.getId()).size()) {
            return true;
        }
        Enumeration enumeration = rootNode.children();
        while(enumeration.hasMoreElements()){
            // 模板判断, 数量判断
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) enumeration.nextElement();
            CodeGroup group = (CodeGroup) node.getUserObject();
            if(node.getChildCount() != templateMap.get(group.getId()).size()){
                return true;
            }
            if(templateEditor != null){
                Enumeration childEnum = node.children();
                while(childEnum.hasMoreElements()){
                    // 模板内容判断
                    DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) childEnum.nextElement();
                    CodeTemplate template = (CodeTemplate) childNode.getUserObject();
                    CodeTemplate tmp = templateEditor.getCodeTemplate();
                    if (Objects.isNull(tmp.getOrder())) {
                        tmp.setOrder(Integer.valueOf(1));
                    }
                    if(template.getId().equals(tmp.getId()) && !template.equals(tmp)){
                        return true;
                    }
                }
            }
        }
    }
    return false;
}
 
Example 19
Source File: TemplatesUI.java    From CodeGen with MIT License 4 votes vote down vote up
@Override
public void apply() {
    List<CodeRoot> roots = new ArrayList<>();
    DefaultTreeModel treeModel = (DefaultTreeModel) templateTree.getModel();
    DefaultMutableTreeNode topNode = (DefaultMutableTreeNode) treeModel.getRoot();
    Enumeration rootEnum = topNode.children();
    // 获取所有root
    while (rootEnum.hasMoreElements()) {
        List<CodeGroup> groups = new ArrayList<>();
        DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) rootEnum.nextElement();
        Enumeration enumeration = rootNode.children();
        // 获取所有组
        while(enumeration.hasMoreElements()){
            List<CodeTemplate> templates = new ArrayList<>();
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) enumeration.nextElement();
            Enumeration childEnum = node.children();
            // 获取所有模板
            while(childEnum.hasMoreElements()){
                DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) childEnum.nextElement();
                CodeTemplate template = (CodeTemplate) childNode.getUserObject();
                if(templateEditor != null){
                    CodeTemplate tmp = templateEditor.getCodeTemplate();
                    if(template.getId().equals(tmp.getId())){
                        template = tmp;
                    }
                }
                if (Objects.isNull(template.getOrder())) {
                    template.setOrder(Integer.valueOf(1));
                }
                templates.add(template);
            }
            CodeGroup group = (CodeGroup) node.getUserObject();
            Collections.sort(templates, Comparator.comparing(CodeTemplate::getOrder));
            group.setTemplates(templates);
            groups.add(group);
        }
        CodeRoot root = (CodeRoot) rootNode.getUserObject();
        root.setGroups(groups);
        roots.add(root);
    }
    settingManager.getTemplates().setRoots(roots);
    reset();
}
 
Example 20
Source File: CamoChoiceDialog.java    From megamek with GNU General Public License v2.0 4 votes vote down vote up
public void setPlayer(IPlayer p) {
    player = p;

    category = player.getCamoCategory();
    if (category.equals(IPlayer.NO_CAMO) && (null != entity) && (p.getColorIndex() >= 0)) {
        filename = (String) camoModel.getValueAt(
                p.getColorIndex(), 0);
    } else {
        filename = player.getCamoFileName();
    }
    if (sourceButton != null) {
        sourceButton.setIcon(generateIcon(category, filename));
    }
    // This cumbersome code takes the category name and transforms it into
    // a TreePath so it can be selected in the dialog
    String[] names = category.split(Pattern.quote("/"));
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) treeCategories
            .getModel().getRoot();
    for (int i = 0; i < names.length; i++) {
        for (Enumeration<?> e = node.children(); e.hasMoreElements();) {
            DefaultMutableTreeNode child = (DefaultMutableTreeNode) e.nextElement();
            if (names[i].equals(child.getUserObject())) {
                node = child;
                break;
            }
        }
    }
    treeCategories.setSelectionPath(new TreePath(node.getPath()));
    fillTable(category);
    int rowIndex = 0;
    for (int i = 0; i < camoModel.getRowCount(); i++) {
        if (((String) camoModel.getValueAt(i, 0)).equals(filename)) {
            rowIndex = i;
            break;
        }
    }
    
    if(rowIndex < 0 || rowIndex >= tableCamo.getRowCount()) {
        System.out.println("Attempting to set invalid camo index " + rowIndex + " for player " + p.getName() + ". Using default instead.");
    } else {
        tableCamo.setRowSelectionInterval(rowIndex, rowIndex);
    }
}