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

The following examples show how to use javax.swing.tree.DefaultMutableTreeNode#getLevel() . 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: 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 2
Source File: InheritanceTree.java    From JDeodorant with MIT License 6 votes vote down vote up
public TreeMap<Integer, Set<String>> getLeavesByLevel() {
	TreeMap<Integer, Set<String>> levelMap = new TreeMap<Integer, Set<String>>();
	Enumeration<DefaultMutableTreeNode> e = rootNode.breadthFirstEnumeration();
	while(e.hasMoreElements()) {
        DefaultMutableTreeNode node = e.nextElement();
        if(node.isLeaf()) {
        	int level = node.getLevel();
        	if(levelMap.containsKey(level)) {
        		levelMap.get(level).add((String) node.getUserObject());
        	}
        	else {
        		Set<String> leaves = new LinkedHashSet<String>();
        		leaves.add((String) node.getUserObject());
        		levelMap.put(level, leaves);
        	}
        }
	}
	return levelMap;
}
 
Example 3
Source File: APKRepatcher.java    From APKRepatcher with MIT License 5 votes vote down vote up
@Override
public void run() {
	createChildren(fileRoot, root);
	DefaultMutableTreeNode currentNode = root.getNextNode();
	if (currentNode.getLevel() == 1)
		tree.expandPath(new TreePath(currentNode.getPath()));
}
 
Example 4
Source File: LastNodeLowerHalfDrop.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
    if (!support.isDrop()) {
        return false;
    }
    support.setShowDropLocation(true);
    if (!support.isDataFlavorSupported(nodesFlavor)) {
        return false;
    }
    // Do not allow a drop on the drag source selections.
    JTree.DropLocation dl = (JTree.DropLocation) support.getDropLocation();
    JTree tree = (JTree) support.getComponent();
    int dropRow = tree.getRowForPath(dl.getPath());
    int[] selRows = tree.getSelectionRows();
    for (int i = 0; i < selRows.length; i++) {
        if (selRows[i] == dropRow) {
            return false;
        }
    }
    // Do not allow MOVE-action drops if a non-leaf node is
    // selected unless all of its children are also selected.
    int action = support.getDropAction();
    if (action == MOVE) {
        return haveCompleteNode(tree);
    }
    // Do not allow a non-leaf node to be copied to a level
    // which is less than its source level.
    TreePath dest = dl.getPath();
    DefaultMutableTreeNode target = (DefaultMutableTreeNode)
            dest.getLastPathComponent();
    TreePath path = tree.getPathForRow(selRows[0]);
    DefaultMutableTreeNode firstNode = (DefaultMutableTreeNode)
            path.getLastPathComponent();
    if (firstNode.getChildCount() > 0
            && target.getLevel() < firstNode.getLevel()) {
        return false;
    }
    return true;
}
 
Example 5
Source File: LastNodeLowerHalfDrop.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected Transferable createTransferable(JComponent c) {
    JTree tree = (JTree) c;
    TreePath[] paths = tree.getSelectionPaths();
    if (paths != null) {
        // Make up a node array of copies for transfer and
        // another for/of the nodes that will be removed in
        // exportDone after a successful drop.
        List<DefaultMutableTreeNode> copies = new ArrayList<>();
        List<DefaultMutableTreeNode> toRemove = new ArrayList<>();
        DefaultMutableTreeNode node = (DefaultMutableTreeNode)
                paths[0].getLastPathComponent();
        DefaultMutableTreeNode copy = copy(node);
        copies.add(copy);
        toRemove.add(node);
        for (int i = 1; i < paths.length; i++) {
            DefaultMutableTreeNode next = (DefaultMutableTreeNode) paths[i]
                    .getLastPathComponent();
            // Do not allow higher level nodes to be added to list.
            if (next.getLevel() < node.getLevel()) {
                break;
            } else if (next.getLevel() > node.getLevel()) {  // child node
                copy.add(copy(next));
                // node already contains child
            } else {                                        // sibling
                copies.add(copy(next));
                toRemove.add(next);
            }
        }
        DefaultMutableTreeNode[] nodes = copies
                .toArray(new DefaultMutableTreeNode[copies.size()]);
        nodesToRemove = toRemove.toArray(
                new DefaultMutableTreeNode[toRemove.size()]);
        return new NodesTransferable(nodes);
    }
    return null;
}
 
Example 6
Source File: ScriptTreeTransferHandler.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
@Override
protected Transferable createTransferable(JComponent c) {
    JTree tree = (JTree) c;
    TreePath[] paths = tree.getSelectionPaths();
    if (paths != null) {
        // Make up a node array of copies for transfer and
        // another for/of the nodes that will be removed in
        // exportDone after a successful drop.
        List<DefaultMutableTreeNode> copies = new ArrayList<DefaultMutableTreeNode>();
        List<DefaultMutableTreeNode> toRemove = new ArrayList<DefaultMutableTreeNode>();
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) paths[0].getLastPathComponent();
        DefaultMutableTreeNode copy = copy(node);
        copies.add(copy);
        toRemove.add(node);
        for (int i = 1; i < paths.length; i++) {
            DefaultMutableTreeNode next =
                    (DefaultMutableTreeNode) paths[i].getLastPathComponent();
            // Do not allow higher level nodes to be added to list.
            if (next.getLevel() < node.getLevel()) {
                break;
            } else if (next.getLevel() > node.getLevel()) { // child node
                copy.add(copy(next));
                // node already contains child
            } else { // sibling
                copies.add(copy(next));
                toRemove.add(next);
            }
        }
        DefaultMutableTreeNode[] nodes =
                copies.toArray(new DefaultMutableTreeNode[copies.size()]);
        nodesToRemove = toRemove.toArray(new DefaultMutableTreeNode[toRemove.size()]);
        return new NodesTransferable(nodes);
    }
    return null;
}
 
Example 7
Source File: ExportToMdTask.java    From Zettelkasten with GNU General Public License v3.0 5 votes vote down vote up
/**
 * This method prepares the html-content for an exported bullet-point. this
 * method is used by {@link #exportEntriesWithCommentsToPDF(javax.swing.tree.DefaultMutableTreeNode, java.lang.StringBuilder, boolean) exportEntriesWithCommentsToPDF()
 * }
 * and
 * {@link #exportEntriesWithCommentsOnlyToPDF(javax.swing.tree.DefaultMutableTreeNode, java.lang.StringBuilder) exportEntriesWithCommentsOnlyToPDF()}.
 *
 * @param node the bullet-node, needed for timestamp and title-text
 * @return a html-snippet with the bullet as headline
 */
private String createExportBullet(DefaultMutableTreeNode node, boolean exportcomments) {
    StringBuilder sb = new StringBuilder("");
    // retrieve bullet-level, so we can use subsections according to the bullet-level
    int bulletlevel = node.getLevel();
    while(bulletlevel-- > 0) {
        sb.append("#");
    }
    // append text
    sb.append(" ").
            append(TreeUtil.getNodeText(node)).
            append(System.lineSeparator()).
            append(System.lineSeparator());
    // check whether comments should be exported as well
    if (exportcomments) {
        // retrieve comment
        String com = desktopObj.getComment(TreeUtil.getNodeTimestamp(node), System.lineSeparator());
        // check for valid comment
        if (com != null && !com.isEmpty()) {
            // append comment-text
            sb.append(resourceMap.getString("comment")).append(System.lineSeparator());
            // append comment
            sb.append(com).append(System.lineSeparator()).append(System.lineSeparator());
        }
    }
    return sb.toString();
}
 
Example 8
Source File: ExportToHtmlTask.java    From Zettelkasten with GNU General Public License v3.0 5 votes vote down vote up
/**
 * This method prepares the html-content for an exported bullet-point. this
 * method is used by {@link #exportEntriesWithComments(javax.swing.tree.DefaultMutableTreeNode, java.lang.StringBuilder, boolean) exportEntriesWithComments()
 * }
 * and
 * {@link #exportEntriesWithCommentsOnly(javax.swing.tree.DefaultMutableTreeNode, java.lang.StringBuilder) exportEntriesWithCommentsOnly()}.
 *
 * @param node the bullet-node, needed for timestamp and title-text
 * @return a html-snippet with the bullet as headline
 */
private String createExportBullet(DefaultMutableTreeNode node) {
    StringBuilder sb = new StringBuilder("");
    // get node's timestamp
    String timestamp = TreeUtil.getNodeTimestamp(node);
    // retrieve bullet-level
    int bulletlevel = node.getLevel();
    // create html-tags for bullet
    sb.append("<h").append(String.valueOf(bulletlevel)).append(">");
    // now create the reference-ankh, so we can use the "scrollToReference" method
    // of the jEditorPane easily each time the user clicks on an entry in the jTree
    // to scroll to that entry in the text field.
    sb.append("<a name=\"");
    sb.append("entry").append(timestamp);
    sb.append("\">&nbsp;</a>");
    sb.append(TreeUtil.getNodeText(node));
    sb.append("</h").append(String.valueOf(bulletlevel)).append(">").append(System.lineSeparator());
    // retrieve node-level, so we can use margins according the the depth of the node in the outline structure
    int lvl = node.getLevel();
    int headerlvl = lvl + 1;
    // set maximum level depth
    if (lvl > 5) {
        lvl = 5;
    }
    if (headerlvl > 5) {
        headerlvl = 5;
    }
    // convert to string for css-class
    String level = String.valueOf(lvl);
    String headerlevel = String.valueOf(headerlvl);
    // add bullet-point to table of content
    exportTableOfContent.append("<h").append(headerlevel).append(" class=\"tocheader").append(level).append("\"><a href=\"#entry").append(timestamp).append("\">").append(TreeUtil.getNodeText(node)).append("</a></h").append(headerlevel).append(">").append(System.lineSeparator());
    return sb.toString();
}
 
Example 9
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
public static void collapseFirstHierarchy(JTree tree) {
  TreeModel model = tree.getModel();
  DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();

  // // Java 9:
  // Collections.list(root.breadthFirstEnumeration()).stream()
  //   .filter(DefaultMutableTreeNode.class::isInstance)
  //   .map(DefaultMutableTreeNode.class::cast)
  //   .takeWhile(node -> node.getLevel() <= 1)
  //   .dropWhile(DefaultMutableTreeNode::isRoot)
  //   .dropWhile(DefaultMutableTreeNode::isLeaf)
  //   .map(DefaultMutableTreeNode::getPath)
  //   .map(TreePath::new)
  //   .forEach(tree::collapsePath);

  // Java 9: Enumeration<TreeNode> e = root.breadthFirstEnumeration();
  Enumeration<?> e = root.breadthFirstEnumeration();
  while (e.hasMoreElements()) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement();
    boolean isOverFirstLevel = node.getLevel() > 1;
    if (isOverFirstLevel) { // Collapse only nodes in the first hierarchy
      return;
    } else if (node.isLeaf() || node.isRoot()) {
      continue;
    }
    collapseNode(tree, node);
  }
}
 
Example 10
Source File: TreeUtil.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * @param tree com.sun.java.swing.JTree
 * @param start com.sun.java.swing.tree.DefaultMutableTreeNode
 */
public static void expandTree(JTree tree, TreeNode start, int level) {
    for (Enumeration children = start.children(); children.hasMoreElements();) {
        DefaultMutableTreeNode dtm = (DefaultMutableTreeNode) children.nextElement();
        //System.out.println(dtm.getUserObject()+" "+dtm.getDepth());
        if (!dtm.isLeaf() && dtm.getLevel() <= level) {
            //
            TreePath tp = new TreePath(dtm.getPath());
            tree.expandPath(tp);
            //
            expandTree(tree, dtm, level);
        }
    }
    return;
}
 
Example 11
Source File: ExportToTexTask.java    From Zettelkasten with GNU General Public License v3.0 4 votes vote down vote up
/**
 * This method prepares the html-content for an exported bullet-point. this method is used by {@link #exportEntriesWithCommentsToPDF(javax.swing.tree.DefaultMutableTreeNode, java.lang.StringBuilder, boolean) exportEntriesWithCommentsToPDF()
 * }
 * and
 * {@link #exportEntriesWithCommentsOnlyToPDF(javax.swing.tree.DefaultMutableTreeNode, java.lang.StringBuilder) exportEntriesWithCommentsOnlyToPDF()}.
 *
 * @param node the bullet-node, needed for timestamp and title-text
 * @return a html-snippet with the bullet as headline
 */
private String createExportBullet(DefaultMutableTreeNode node, boolean exportcomments) {
    StringBuilder sb = new StringBuilder("");
    // check whether comments should be exported as well
    if (exportcomments) {
        // retrieve comment
        String com = desktopObj.getComment(TreeUtil.getNodeTimestamp(node), System.lineSeparator());
        // check for valid comment
        if (com != null && !com.isEmpty()) {
            // append comment
            sb.append(Tools.lineWrapText(com, 40, "%"));
        }
    }
    // retrieve bullet-level, so we can use subsections according to the bullet-level
    int bulletlevel = node.getLevel();
    // check which level the bullet is, so we can either indicate this heading as section
    // or sub(sub)section...
    switch (bulletlevel) {
        case 1:
            sb.append("\\section{");
            break;
        case 2:
            sb.append("\\subsection{");
            break;
        case 3:
            sb.append("\\subsubsection{");
            break;
        case 4:
            sb.append("\\paragraph{");
            break;
        case 5:
            sb.append("\\subparagraph{");
            break;
    }
    // get bullet-text
    String text = TreeUtil.getNodeText(node);
    // get converted special chars and enquotes quotes
    text = getConvertedTex(text);
    // append text
    sb.append(text).append("}").append(System.lineSeparator()).append(System.lineSeparator());
    return sb.toString();
}
 
Example 12
Source File: ExportToHtmlTask.java    From Zettelkasten with GNU General Public License v3.0 4 votes vote down vote up
/**
 * This method prepares the html-content for an exported entry. this method
 * is used by {@link #exportEntriesWithComments(javax.swing.tree.DefaultMutableTreeNode, java.lang.StringBuilder, boolean) exportEntriesWithComments()
 * }
 * and
 * {@link #exportEntriesWithCommentsOnly(javax.swing.tree.DefaultMutableTreeNode, java.lang.StringBuilder) exportEntriesWithCommentsOnly()}.
 *
 * @param node the entry-node, needed for timestamp and entry-text
 * @return a html-snippet with the entry as content
 */
private String createExportEntry(DefaultMutableTreeNode node) {
    // retrieve node's timestamp
    String timestamp = TreeUtil.getNodeTimestamp(node);
    // we now want to check whether the user has made modifications to the entry's
    // content, which are only made to the desktop (the content of the entry in the main database
    // is not changed, so you can edit the desktop-entry without changing the entry's original
    // content - this is useful when you want to add some words/phrases between entries etc., which
    // should be applied only to the final text on the desktop, but not to the original entries).
    //
    // in case we have modified an entry on the desktop, this entry has a "content" element. to
    // retrieve the correct entry, we need to look for the unique timestamp of that entry - since
    // an entry could appear multiple times on the desktop, thus the entry number itself is no
    // valid value for retrieving the right entry. Therefore, each treenode has a user-object
    // assigned, which holds the unique timestamp
    String text = desktopObj.retrieveModifiedEntryContentFromTimestamp(timestamp);
    // retrieve entry-number
    int nr = TreeUtil.extractEntryNumberFromNode(node);
    // if nothing found, retrieve regular entry
    // that means, if the entry with the unique-timestamp has no or an empty content-element, the
    // entry was not modified - thus we retrieve the "original" entry.
    if (null == text || text.isEmpty()) {
        text = HtmlUbbUtil.getHtmlContentForDesktop(dataObj, bibtexObj, settingsObj, nr, isHeadingVisible, zettelNumberAsPrefix, true, true);
    } // else if we have a modified entry-content, we still need to convert its
    // ubb-tags to HTML. this is done here...
    else {
        // get the html-text for an entry which content is passed as parameter...
        text = HtmlUbbUtil.getHtmlContentForDesktop(dataObj, bibtexObj, settingsObj, text, nr, isHeadingVisible, zettelNumberAsPrefix, true, true);
    }
    // if the user wishes to remove multiple line-breaks, do this here
    if (settingsObj.getRemoveLinesForDesktopExport()) {
        text = text.replace("<br><br>", "<br>");
    }
    // now create the reference-ankh, so we can use the "scrollToReference" method
    // of the jEditorPane easily each time the user clicks on an entry in the jTree
    // to scroll to that entry in the text field.
    StringBuilder sb = new StringBuilder("");
    sb.append("<a name=\"");
    sb.append("entry").append(timestamp);
    sb.append("\">&nbsp;</a>").append(System.lineSeparator());
    sb.append(text);
    // retrieve entry's title
    String title = dataObj.getZettelTitle(nr);
    // if we have no title, use enty number instead
    if (title.isEmpty()) {
        title = resourceMap.getString("entryText") + " " + String.valueOf(nr);
    }
    // retrieve node-level, so we can use margins according the the depth of the node in the outline structure
    int lvl = node.getLevel();
    // set maximum level depth
    if (lvl > 5) {
        lvl = 5;
    }
    // convert to string for css-class
    String level = String.valueOf(lvl);
    // create toc-entry
    exportTableOfContent.append("<p class=\"tocentry").append(level).append("\"><a href=\"#entry").append(timestamp).append("\">").append(title).append("</a></p>").append(System.lineSeparator());
    // return result
    return sb.toString();
}
 
Example 13
Source File: NetworkDisplay.java    From yeti with MIT License 4 votes vote down vote up
@Override
public Component getTreeCellRendererComponent(JTree tree,
        Object value,
        boolean selected,
        boolean expanded,
        boolean leaf,
        int row,
        boolean hasFocus) {

    if (value instanceof DefaultMutableTreeNode) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;

        switch (node.getLevel()) {
            case 0:
                return networkNodeRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
        }
        if (node.getUserObject().getClass() == Domain.class) {
            return domainNodeRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
        } else if (node.getUserObject().getClass() == Host.class) {
            return hostNodeRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
        } else if (node.getUserObject().getClass() == Ip.class) {
            return ipNodeRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
        } else if (node.getUserObject().getClass() == Attribute.class) {
            return attrNodeRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
        } else if (node.getUserObject().getClass() == AttributeValue.class) {
            if (((AttributeValue) node.getUserObject()).getType().compareTo("vuln") == 0) {
                return attrVulnNodeRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
            } else {
                return attrConfigNodeRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
            }
        } else if (node.getUserObject().getClass() == Hosts.class) {
            return hostsNodeRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
        } else if (node.getUserObject().getClass() == Port.class) {
            DefaultTreeCellRenderer pr = null;
            if (((Port) node.getUserObject()).getState().compareTo("open") == 0) {
                pr = getPortRenderer(openPort);
            } else if (((Port) node.getUserObject()).getState().compareTo("closed") == 0) {
                pr = getPortRenderer(closedPort);
            } else if (((Port) node.getUserObject()).getState().compareTo("filtered") == 0) {
                pr = getPortRenderer(filteredPort);
            }
            //String label = String.format("%d : %s",((port__)node.getUserObject()).getPortNumber(),((port__)node.getUserObject()).getServiceName());
            if (pr != null) {
                return pr.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
            }
        }
    }
    return networkNodeRenderer;
}
 
Example 14
Source File: MultilineTreeCellRenderer.java    From consulo with Apache License 2.0 4 votes vote down vote up
private int getAvailableWidth(Object forValue, JTree tree) {
  DefaultMutableTreeNode node = (DefaultMutableTreeNode)forValue;
  int busyRoom = tree.getInsets().left + tree.getInsets().right + getChildIndent(tree) * node.getLevel();
  return tree.getVisibleRect().width - busyRoom - 2;
}