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

The following examples show how to use javax.swing.tree.DefaultMutableTreeNode#remove() . 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: ProcessingComponent.java    From mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Removes the selected module in the tvProcessingList from the list
 */
private void removeModule() {
  DefaultMutableTreeNode selected = getSelectedItem(tvProcessing);
  if (selected == null)
    return;

  if (selected instanceof DPPModuleTreeNode) {
    DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selected.getParent();
    if (parent instanceof DPPMSLevelTreeNode && ((DPPMSLevelTreeNode) parent).isEnabled()) {
      parent.remove(selected);
      logger.finest("Removed module " + ((DPPModuleTreeNode) selected).getModule().getName()
          + " from processing list.");
    }
  } else {
    logger.finest("Cannot remove item " + selected.toString() + " from processing list.");
  }
  ((DefaultTreeModel) tvProcessing.getModel()).reload();
  expandAllNodes(tvProcessing);
}
 
Example 2
Source File: DefaultModulesPanel.java    From opt4j with MIT License 6 votes vote down vote up
/**
 * Removes empty categories. This method can create some new empty
 * categories!
 * 
 * @param current
 *            the current node
 * @return true if an empty category was removed
 */
private boolean removeEmptyCategories(DefaultMutableTreeNode current) {
	if (!current.children().hasMoreElements()) {
		return false;
	}

	TreeNode node = current.getFirstChild();
	boolean removed = false;
	while (node != null) {
		DefaultMutableTreeNode n = (DefaultMutableTreeNode) node;
		node = current.getChildAfter(n);

		if (n.isLeaf()) {
			if (n instanceof CategoryTreeNode && n.getChildCount() == 0) {
				DefaultMutableTreeNode parent = (DefaultMutableTreeNode) n.getParent();
				parent.remove(n);
				removed = true;
			}
		} else {
			removed = removed || removeEmptyCategories(n);
		}
	}
	return removed;
}
 
Example 3
Source File: TreePanel.java    From nmonvisualizer with Apache License 2.0 6 votes vote down vote up
@Override
public final void dataRemoved(DataSet data) {
    DefaultMutableTreeNode root = (DefaultMutableTreeNode) ((DefaultTreeModel) tree.getModel()).getRoot();

    for (int i = 0; i < root.getChildCount(); i++) {
        DataSet toSearch = (DataSet) ((DefaultMutableTreeNode) root.getChildAt(i)).getUserObject();

        if (toSearch.equals(data)) {
            Object removed = root.getChildAt(i);

            root.remove(i);

            ((javax.swing.tree.DefaultTreeModel) tree.getModel()).nodesWereRemoved(root, new int[] { i },
                    new Object[] { removed });

            // to remove a node requires it to be selected, so move the selection to the root
            tree.setSelectionPath(new TreePath(root));

            break;
        }
    }
}
 
Example 4
Source File: PlayPanel.java    From HubPlayer with GNU General Public License v3.0 6 votes vote down vote up
public void removeSongNodeInTreeList(JTree tree, int index,
		SongNode songNode) {
	DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree.getModel()
			.getRoot();
	DefaultMutableTreeNode list = (DefaultMutableTreeNode) root
			.getChildAt(index);

	list.remove(songNode);

	// 列表名更新
	String listName = (String) list.getUserObject();
	listName = listName.substring(0, listName.lastIndexOf("[")) + "["
			+ list.getChildCount() + "]";
	list.setUserObject(listName);

	// 如果这里不更新树的话 会不正确显示
	tree.updateUI();

}
 
Example 5
Source File: InspectorWindow.java    From megan-ce with GNU General Public License v3.0 6 votes vote down vote up
/**
 * delete all the selected nodes
 */
public void deleteSelectedNodes() {
    DefaultTreeModel model = (DefaultTreeModel) dataTree.getModel();
    TreePath[] selectedPaths = dataTree.getSelectionPaths();
    if (selectedPaths != null) {
        for (TreePath selectedPath : selectedPaths) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectedPath.getLastPathComponent();
            node.removeAllChildren();
            model.nodeStructureChanged(node);
            DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent();
            if (parent != null) {
                parent.remove(node);
                model.nodeStructureChanged(parent);
            }
        }
    }
}
 
Example 6
Source File: LibraryOperation.java    From HubPlayer with GNU General Public License v3.0 6 votes vote down vote up
public void removeSongNodeInTreeList(JTree tree, int index) {
	DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree
			.getModel().getRoot();
	DefaultMutableTreeNode list = (DefaultMutableTreeNode) root
			.getChildAt(index);

	list.remove(songNode);

	// 列表名更新
	String listName = (String) list.getUserObject();
	listName = listName.substring(0, listName.lastIndexOf("[")) + "["
			+ list.getChildCount() + "]";
	list.setUserObject(listName);

	// 如果这里不更新树的话 会不正确显示
	tree.updateUI();

}
 
Example 7
Source File: SunJDKParser.java    From tda with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void renormalizeMonitorDepth(DefaultMutableTreeNode monitorNode, int index) {
    // First, remove all duplicates of the item at index "index"
    DefaultMutableTreeNode threadNode1 = (DefaultMutableTreeNode) monitorNode.getChildAt(index);
    ThreadInfo mi1 = (ThreadInfo) threadNode1.getUserObject();
    int i = index + 1;
    while (i < monitorNode.getChildCount()) {
        DefaultMutableTreeNode threadNode2 = (DefaultMutableTreeNode) monitorNode.getChildAt(i);
        ThreadInfo mi2 = (ThreadInfo) threadNode2.getUserObject();
        if (mi1.getName().equals(mi2.getName())) {
            if (threadNode2.getChildCount() > 0) {
                threadNode1.add((DefaultMutableTreeNode) threadNode2.getFirstChild());
                monitorNode.remove(i);
                continue;
            }
        }
        i++;
    }

    // Second, recurse into item "index"
    renormalizeThreadDepth(threadNode1);
}
 
Example 8
Source File: ProcessingComponent.java    From mzmine2 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Removes the selected module in the tvProcessingList from the list
 */
private void removeModule() {
  DefaultMutableTreeNode selected = getSelectedItem(tvProcessing);
  if (selected == null)
    return;

  if (selected instanceof DPPModuleTreeNode) {
    DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selected.getParent();
    if (parent instanceof DPPMSLevelTreeNode && ((DPPMSLevelTreeNode) parent).isEnabled()) {
      parent.remove(selected);
      logger.finest("Removed module " + ((DPPModuleTreeNode) selected).getModule().getName()
          + " from processing list.");
    }
  } else {
    logger.finest("Cannot remove item " + selected.toString() + " from processing list.");
  }
  ((DefaultTreeModel) tvProcessing.getModel()).reload();
  expandAllNodes(tvProcessing);
}
 
Example 9
Source File: SelectLocationView.java    From jd-gui with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected void populate(Set<URI> uris, DefaultMutableTreeNode node) {
    if (node instanceof TreeNodeExpandable) {
        ((TreeNodeExpandable)node).populateTreeNode(api);

        int i = node.getChildCount();

        while (i-- > 0) {
            T child = (T)node.getChildAt(i);

            if (uris.contains(child.getUri())) {
                populate(uris, child);
            } else {
                node.remove(i);
            }
        }
    }
}
 
Example 10
Source File: Visitor.java    From RefactoringMiner with MIT License 6 votes vote down vote up
private DefaultMutableTreeNode deleteNode(AnonymousClassDeclaration childAnonymous) {
	Enumeration enumeration = root.postorderEnumeration();
	DefaultMutableTreeNode childNode = findNode(childAnonymous);
	
	DefaultMutableTreeNode parentNode = root;
	while(enumeration.hasMoreElements()) {
		DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)enumeration.nextElement();
		AnonymousClassDeclarationObject currentAnonymous = (AnonymousClassDeclarationObject)currentNode.getUserObject();
		if(currentAnonymous != null && isParent(childAnonymous, currentAnonymous.getAstNode())) {
			parentNode = currentNode;
			break;
		}
	}
	parentNode.remove(childNode);
	AnonymousClassDeclarationObject childAnonymousObject = (AnonymousClassDeclarationObject)childNode.getUserObject();
	childAnonymousObject.setAstNode(null);
	return parentNode;
}
 
Example 11
Source File: FilterTreeModel.java    From swing_library with MIT License 5 votes vote down vote up
/**
 * 
 * @param root
 * @return boolean bad leaves were returned
 */
private boolean removeBadLeaves(DefaultMutableTreeNode root) {

	// no bad leaves yet
	boolean badLeaves = false;

	// reference first leaf
	DefaultMutableTreeNode leaf = root.getFirstLeaf();

	// if leaf is root then its the only node
	if (leaf.isRoot())
		return false;

	int leafCount = root.getLeafCount(); // this get method changes if in for loop so have to define outside of it
	for (int i = 0; i < leafCount; i++) {

		DefaultMutableTreeNode nextLeaf = leaf.getNextLeaf();

		// if it does not start with the text then snip it off its parent
		if (!filter.accepts(filterText, leaf.getUserObject().toString())) {
			DefaultMutableTreeNode parent = (DefaultMutableTreeNode) leaf.getParent();

			if (parent != null)
				parent.remove(leaf);

			badLeaves = true;
		}
		leaf = nextLeaf;
	}
	return badLeaves;
}
 
Example 12
Source File: FilteredTree.java    From swing_library with MIT License 5 votes vote down vote up
/**
 * 
 * @param root
 * @return boolean bad leaves were returned
 */
private boolean removeBadLeaves(DefaultMutableTreeNode root) {

	// no bad leaves yet
	boolean badLeaves = false;

	// reference first leaf
	DefaultMutableTreeNode leaf = root.getFirstLeaf();

	// if leaf is root then its the only node
	if (leaf.isRoot())
		return false;

	int leafCount = root.getLeafCount(); // this get method changes if in for loop so have to define outside of it
	for (int i = 0; i < leafCount; i++) {

		DefaultMutableTreeNode nextLeaf = leaf.getNextLeaf();

		// if it does not start with the text then snip it off its parent
		if (!leaf.getUserObject().toString().startsWith(textToMatch)) {
			DefaultMutableTreeNode parent = (DefaultMutableTreeNode) leaf.getParent();

			if (parent != null)
				parent.remove(leaf);

			badLeaves = true;
		}
		leaf = nextLeaf;
	}
	return badLeaves;
}
 
Example 13
Source File: BaseTreePage.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void expandTreeToDepth(DefaultMutableTreeNode node, int depth, String userId, List<ListOptionSerialized> blankRestrictedTools, List<String> accessAdminNodeIds, boolean onlyAccessNodes, boolean shopping, boolean shoppingPeriodTool, String filterSearch){
	projectLogic.addChildrenNodes(node, userId, blankRestrictedTools, onlyAccessNodes, accessAdminNodeIds, shopping, shoppingPeriodTool);
	//set expand flag to true so to not look for children again:
	((NodeModel) node.getUserObject()).setAddedDirectChildrenFlag(true);
	getTree().getTreeState().expandNode(node);
	if(depth > 0){
		//recursive function stopper:
		int newDepth = depth - 1;
		//count down backwards since we could be deleting these children nodes
		for(int i = node.getChildCount() - 1; i >= 0; i--){
			expandTreeToDepth((DefaultMutableTreeNode) node.getChildAt(i), newDepth, userId, blankRestrictedTools, accessAdminNodeIds, onlyAccessNodes, shopping, shoppingPeriodTool, filterSearch);
		}
	}else{
		//make sure all children are collapsed and filter out the ones that need to be filtered
		//count down backwards since we could be deleting these children nodes
		for(int i = node.getChildCount() - 1; i >= 0; i--){
			getTree().getTreeState().collapseNode(node.getChildAt(i));
			String nodeTitle = ((NodeModel) ((DefaultMutableTreeNode) node.getChildAt(i)).getUserObject()).getNode().description.toLowerCase();
			if(filterSearch != null && !"".equals(filterSearch.trim()) && !nodeTitle.contains(filterSearch.toLowerCase())){
				//delete this child:
				node.remove(i);
			}
		}
	}
	//check if all of the children have been removed (but don't delete root node)
	if(node.getParent() != null && node.getChildCount() == 0){
		((DefaultMutableTreeNode) node.getParent()).remove(node);
	}
}
 
Example 14
Source File: IfStatementExpressionAnalyzer.java    From JDeodorant with MIT License 5 votes vote down vote up
public DefaultMutableTreeNode getRemainingExpression(Expression expressionToBeRemoved) {
	DefaultMutableTreeNode newRoot = new DefaultMutableTreeNode();
	processExpression(newRoot, completeExpression);
	DefaultMutableTreeNode leaf = newRoot.getFirstLeaf();
	while(leaf != null) {
		Expression expression = (Expression)leaf.getUserObject();
		if(expression.equals(expressionToBeRemoved)) {
			DefaultMutableTreeNode parent = (DefaultMutableTreeNode)leaf.getParent();
			if(parent != null) {
				DefaultMutableTreeNode grandParent = (DefaultMutableTreeNode)parent.getParent();
				DefaultMutableTreeNode sibling = null;
				if(leaf.getNextSibling() != null) {
					sibling = leaf.getNextSibling();
				}
				else if(leaf.getPreviousSibling() != null) {
					sibling = leaf.getPreviousSibling();
				}
				if(grandParent != null) {
					int parentIndex = grandParent.getIndex(parent);
					grandParent.remove(parent);
					grandParent.insert(sibling, parentIndex);
				}
				else {
					newRoot = sibling;
				}
				break;
			}
			else {
				newRoot = null;
				break;
			}
		}
		leaf = leaf.getNextLeaf();
	}
	return newRoot;
}
 
Example 15
Source File: GroupedBandChoosingStrategy.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private void removeEmptyGroups(DefaultMutableTreeNode root, Map<String, Integer> groupNodeMap) {
    DefaultMutableTreeNode rootChild = (DefaultMutableTreeNode) root.getFirstChild();
    while (rootChild != null) {
        DefaultMutableTreeNode nextChild = rootChild.getNextSibling();
        if (rootChild.getChildCount() == 0 && groupNodeMap.containsKey(rootChild.getUserObject().toString())) {
            root.remove(rootChild);
        }
        rootChild = nextChild;
    }
}
 
Example 16
Source File: BaseTreePage.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void expandTreeToDepth(DefaultMutableTreeNode node, int depth, String userId, List<ListOptionSerialized> blankRestrictedTools, List<String> accessAdminNodeIds, boolean onlyAccessNodes, boolean shopping, boolean shoppingPeriodTool, String filterSearch){
	projectLogic.addChildrenNodes(node, userId, blankRestrictedTools, onlyAccessNodes, accessAdminNodeIds, shopping, shoppingPeriodTool);
	//set expand flag to true so to not look for children again:
	((NodeModel) node.getUserObject()).setAddedDirectChildrenFlag(true);
	getTree().getTreeState().expandNode(node);
	if(depth > 0){
		//recursive function stopper:
		int newDepth = depth - 1;
		//count down backwards since we could be deleting these children nodes
		for(int i = node.getChildCount() - 1; i >= 0; i--){
			expandTreeToDepth((DefaultMutableTreeNode) node.getChildAt(i), newDepth, userId, blankRestrictedTools, accessAdminNodeIds, onlyAccessNodes, shopping, shoppingPeriodTool, filterSearch);
		}
	}else{
		//make sure all children are collapsed and filter out the ones that need to be filtered
		//count down backwards since we could be deleting these children nodes
		for(int i = node.getChildCount() - 1; i >= 0; i--){
			getTree().getTreeState().collapseNode(node.getChildAt(i));
			String nodeTitle = ((NodeModel) ((DefaultMutableTreeNode) node.getChildAt(i)).getUserObject()).getNode().description.toLowerCase();
			if(filterSearch != null && !"".equals(filterSearch.trim()) && !nodeTitle.contains(filterSearch.toLowerCase())){
				//delete this child:
				node.remove(i);
			}
		}
	}
	//check if all of the children have been removed (but don't delete root node)
	if(node.getParent() != null && node.getChildCount() == 0){
		((DefaultMutableTreeNode) node.getParent()).remove(node);
	}
}
 
Example 17
Source File: ActionUrl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void removePathFromActionsTree(JTree tree, ActionUrl url) {
  if (url.myComponent == null) return;
  final TreePath treePath = CustomizationUtil.getTreePath(tree, url);
  if (treePath == null) return;
  DefaultMutableTreeNode node = (DefaultMutableTreeNode)treePath.getLastPathComponent();
  final int absolutePosition = url.getAbsolutePosition();
  if (node.getChildCount() > absolutePosition && absolutePosition >= 0) {
    DefaultMutableTreeNode child = (DefaultMutableTreeNode)node.getChildAt(absolutePosition);
    if (child.getUserObject().equals(url.getComponent())) {
      node.remove(child);
    }
  }
}
 
Example 18
Source File: Home.java    From dctb-utfpr-2018-1 with Apache License 2.0 5 votes vote down vote up
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
   selectedNode = (DefaultMutableTreeNode) treeMem.getLastSelectedPathComponent();
    if (selectedNode != null){
        DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selectedNode.getParent();
        parent.remove(selectedNode);
        tree.reload(parent);
    }
}
 
Example 19
Source File: TreeNodeTest.java    From jenetics with Apache License 2.0 5 votes vote down vote up
@Test
public void remove() {
	final TreeNode<Integer> tree = newTree(5, new Random(123));
	final DefaultMutableTreeNode stree = newSwingTree(5, new Random(123));

	tree.remove(0);
	stree.remove(0);
	Assert.assertTrue(equals(tree, stree));
}
 
Example 20
Source File: SunJDKParser.java    From tda with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void renormalizeBlockingThreadTree(MonitorMap mmap, Map directChildMap) {
    Map allBlockingThreadsMap = new HashMap(directChildMap); // All threads that are blocking at least one other thread

    // First, renormalize based on monitors to get our unique tree
    // Tree will be unique as long as there are no deadlocks aka monitor loops
    for (Iterator iter = mmap.iterOfKeys(); iter.hasNext();) {
        String monitor1 = (String) iter.next();
        Map[] threads1 = mmap.getFromMonitorMap(monitor1);

        DefaultMutableTreeNode thread1Node = (DefaultMutableTreeNode) allBlockingThreadsMap.get(monitor1);
        if (thread1Node == null) {
            continue;
        }

        // Get information on the one thread holding this lock
        Iterator it = threads1[MonitorMap.LOCK_THREAD_POS].keySet().iterator();
        if (!it.hasNext()) {
            continue;
        }
        String threadLine1 = (String) it.next();

        for (Iterator iter2 = mmap.iterOfKeys(); iter2.hasNext();) {
            String monitor2 = (String) iter2.next();
            if (monitor1 == monitor2) {
                continue;
            }

            Map[] threads2 = mmap.getFromMonitorMap(monitor2);
            if (threads2[MonitorMap.WAIT_THREAD_POS].containsKey(threadLine1)) {
                // Get the node of the thread that is holding this lock
                DefaultMutableTreeNode thread2Node = (DefaultMutableTreeNode) allBlockingThreadsMap.get(monitor2);
                // Get the node of the monitor itself
                DefaultMutableTreeNode monitor2Node = (DefaultMutableTreeNode) thread2Node.getFirstChild();

                // If a redundant node for thread2 exists with no children, remove it
                // To compare, we have to remove "Thread - " from the front of display strings
                for (int i = 0; i < monitor2Node.getChildCount(); i++) {
                    DefaultMutableTreeNode child2 = (DefaultMutableTreeNode) monitor2Node.getChildAt(i);
                    if (child2.toString().substring(9).equals(threadLine1) && child2.getChildCount() == 0) {
                        monitor2Node.remove(i);
                        break;
                    }
                }

                // Thread1 is blocked by monitor2 held by thread2, so move thread1 under thread2
                monitor2Node.insert(thread1Node, 0);
                directChildMap.remove(monitor1);
                break;
            }
        }
    }

    allBlockingThreadsMap.clear();

    // Second, renormalize top level based on threads for cases where one thread holds multiple monitors
    boolean changed = false;
    do {
        changed = false;
        for (Iterator iter = directChildMap.entrySet().iterator(); iter.hasNext();) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) ((Map.Entry) iter.next()).getValue();
            if (checkForDuplicateThreadItem(directChildMap, node)) {
                changed = true;
                break;
            }
        }
    } while (changed);

    // Third, renormalize lower levels of the tree based on threads for cases where one thread holds multiple monitors
    for (Iterator iter = directChildMap.entrySet().iterator(); iter.hasNext();) {
        renormalizeThreadDepth((DefaultMutableTreeNode) ((Map.Entry) iter.next()).getValue());
    }
}