Java Code Examples for javax.swing.tree.MutableTreeNode

The following examples show how to use javax.swing.tree.MutableTreeNode. These examples are extracted from open source projects. 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 Project: rest-client   Source File: JSONTree.java    License: Apache License 2.0 6 votes vote down vote up
/**
* 
* @Title      : removeCurrentNode 
* @Description: Remove the currently selected node. 
* @Param      :  
* @Return     : void
* @Throws     :
 */
public void removeCurrentNode()
{
    TreePath currentSelection = tree.getSelectionPath();
    if (null == currentSelection)
    {
        return;
    }

    CheckBoxTreeNode currentNode = (CheckBoxTreeNode) (currentSelection.getLastPathComponent());
    MutableTreeNode parent = (MutableTreeNode) (currentNode.getParent());
    if (null != parent)
    {
        treeModel.removeNodeFromParent(currentNode);
        return;
    }

    // Either there was no selection, or the root was selected.
    toolkit.beep();
}
 
Example 2
Source Project: consulo   Source File: GroupNode.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Implementation of javax.swing.tree.DefaultTreeModel#removeNodeFromParent(javax.swing.tree.MutableTreeNode) for multiple nodes.
 * Fires a single event, or does nothing when nodes is empty.
 *
 * @param treeModel to fire the treeNodesRemoved event on
 * @param parent    the parent
 * @param nodes     must all be children of parent
 */
private static void removeNodesFromParent(@Nonnull DefaultTreeModel treeModel, @Nonnull GroupNode parent, @Nonnull List<? extends MutableTreeNode> nodes) {
  int count = nodes.size();
  if (count == 0) {
    return;
  }
  ObjectIntHashMap<MutableTreeNode> ordering = new ObjectIntHashMap<>(count);
  for (MutableTreeNode node : nodes) {
    ordering.put(node, parent.getIndex(node));
  }
  Collections.sort(nodes, Comparator.comparingInt(ordering::get)); // need ascending order
  int[] indices = ordering.getValues();
  Arrays.sort(indices);
  for (int i = count - 1; i >= 0; i--) {
    parent.remove(indices[i]);
  }
  treeModel.nodesWereRemoved(parent, indices, nodes.toArray());
}
 
Example 3
private MutableTreeNode wrap(final Tree tree) {
	if (tree == null) {
		return null;
	}
	DefaultMutableTreeNode root = new DefaultMutableTreeNode(tree) {
		@Override
		public String toString() {
			return treeTextProvider.getText((Tree) getUserObject());
		}


	};

	for (int i = 0; i < tree.getChildCount(); i++) {
		root.add(wrap(tree.getChild(i)));
	}
	return root;
}
 
Example 4
Source Project: ISO8583   Source File: SortTreeHelper.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void sort(DefaultMutableTreeNode parent) {
	int n = parent.getChildCount();
	for (int i = 0; i < n - 1; i++) {
		int min = i;
		for (int j = i + 1; j < n; j++) {
			if (tnc.compare((DefaultMutableTreeNode) parent.getChildAt(min), (DefaultMutableTreeNode) parent.getChildAt(j)) > 0) {
				min = j;
			}
		}
		if (i != min) {
			MutableTreeNode a = (MutableTreeNode) parent.getChildAt(i);
			MutableTreeNode b = (MutableTreeNode) parent.getChildAt(min);
			parent.insert(b, i);
			parent.insert(a, min);
			
			updateTree = true;
		}
	}
}
 
Example 5
Source Project: tda   Source File: SunJDKParser.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private boolean checkForDuplicateThreadItem(Map directChildMap, DefaultMutableTreeNode node1) {
    ThreadInfo mi1 = (ThreadInfo) node1.getUserObject();
    String name1 = mi1.getName();

    for (Iterator iter2 = directChildMap.entrySet().iterator(); iter2.hasNext();) {
        DefaultMutableTreeNode node2 = (DefaultMutableTreeNode) ((Map.Entry) iter2.next()).getValue();
        if (node1 == node2) {
            continue;
        }

        ThreadInfo mi2 = (ThreadInfo) node2.getUserObject();
        if (name1.equals(mi2.getName()) && node2.getChildCount() > 0) {
            node1.add((MutableTreeNode) node2.getFirstChild());
            iter2.remove();
            return true;
        }
    }

    return false;
}
 
Example 6
private void rangeAxisConfigRemoved(int index, RangeAxisConfig rangeAxis) {
	removeNodeFromParent((MutableTreeNode) root.getChildAt(index + NUMBER_OF_PERMANENT_DIMENSIONS));

	reload();
	plotConfigTree.expandAll();

	// Acquire new selection element
	int childCount = root.getChildCount();
	Object newSelection = null;

	if (childCount > NUMBER_OF_PERMANENT_DIMENSIONS) {
		newSelection = root.getChildAt(childCount - 1);
	} else {
		newSelection = root;
	}

	// change selection path
	TreePath path = new TreePath(getPathToRoot((TreeNode) newSelection));
	makeVisibleAndSelect(path);
}
 
Example 7
Source Project: weblaf   Source File: WebTreeNode.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Removes {@code child} from its present parent (if it has a parent), sets the child's parent to this node,
 * and then adds the child to this node's child {@link List} at index {@code childIndex}.
 * {@code child} must not be {@code null} and must not be an ancestor of this node.
 *
 * @param child child node to insert under this node
 * @param index index in this node's child {@link List} where this node is to be inserted
 * @throws IllegalStateException          if this node does not allow children
 * @throws IllegalArgumentException       if {@code child} is null or is an ancestor of this node
 * @throws ArrayIndexOutOfBoundsException if {@code childIndex} is out of bounds
 * @see #isNodeDescendant(WebTreeNode)
 */
@Override
public void insert ( @NotNull final MutableTreeNode child, final int index )
{
    if ( !allowsChildren )
    {
        throw new IllegalStateException ( "Node does not allow children" );
    }
    if ( isNodeAncestor ( ( N ) child ) )
    {
        throw new IllegalArgumentException ( "New child is an ancestor" );
    }

    final N oldParent = ( N ) child.getParent ();
    if ( oldParent != null )
    {
        oldParent.remove ( child );
    }
    child.setParent ( this );
    if ( children == null )
    {
        children = new ArrayList<N> ();
    }
    children.add ( index, ( N ) child );
}
 
Example 8
Source Project: nextreports-designer   Source File: StructureTreeModel.java    License: Apache License 2.0 6 votes vote down vote up
public void removeNodeFromParent(MutableTreeNode node) {
    if (!filterIsActive) {
        super.removeNodeFromParent(node);
    } else {
        MutableTreeNode parent = (MutableTreeNode) node.getParent();
        if (parent == null)
            throw new IllegalArgumentException("node does not have a parent.");

        int[] childIndex = new int[1];
        Object[] removedArray = new Object[1];

        childIndex[0] = ((StructureTreeNode)parent).getIndex(node, filterIsActive);            
        if ((childIndex[0] != -1) && ((StructureTreeNode)node).isVisible()) {
            node.removeFromParent();
            removedArray[0] = node;
            nodesWereRemoved(parent, childIndex, removedArray);
        }
    }
}
 
Example 9
Source Project: dsworkbench   Source File: TribeNode.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void insert(MutableTreeNode child, int index) {
    super.insert(child, index);
    Collections.sort(this.children, new Comparator() {

        @Override
        public int compare(Object o1, Object o2) {
            if (o1 instanceof TagNode) {
                return -1;
            }
            if (o2 instanceof TagNode) {
                return 1;
            }
            return o1.toString().compareToIgnoreCase(o2.toString());
        }
    });
}
 
Example 10
Source Project: Zettelkasten   Source File: TreeUtil.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * This method selects the first entry in a jTree that start with the text
 * that is entered in the filter-textfield.
 *
 * @param tree the jTree where the item should be selected
 * @param textfield the related filtertextfield that contains the user-input
 */
public static void selectByTyping(javax.swing.JTree tree, javax.swing.JTextField textfield) {
    DefaultTreeModel dtm = (DefaultTreeModel) tree.getModel();
    MutableTreeNode root = (MutableTreeNode) dtm.getRoot();
    String text = textfield.getText().toLowerCase();
    if (root != null && !text.isEmpty()) {
        for (int cnt = 0; cnt < dtm.getChildCount(root); cnt++) {
            MutableTreeNode child = (MutableTreeNode) dtm.getChild(root, cnt);
            String childtext = child.toString().toLowerCase();
            if (childtext.startsWith(text)) {
                TreePath tp = new TreePath(root);
                tp = tp.pathByAddingChild(child);
                tree.setSelectionPath(tp);
                tree.scrollPathToVisible(tp);
                return;
            }
        }
    }
}
 
Example 11
Source Project: java-swing-tips   Source File: MainPanel.java    License: MIT License 6 votes vote down vote up
private static void sort2(DefaultMutableTreeNode parent) {
  int n = parent.getChildCount();
  for (int i = 0; i < n - 1; i++) {
    int min = i;
    for (int j = i + 1; j < n; j++) {
      if (tnc.compare((DefaultMutableTreeNode) parent.getChildAt(min),
          (DefaultMutableTreeNode) parent.getChildAt(j)) > 0) {
        min = j;
      }
    }
    if (i != min) {
      SWAP_COUNTER.getAndIncrement();
      MutableTreeNode a = (MutableTreeNode) parent.getChildAt(i);
      MutableTreeNode b = (MutableTreeNode) parent.getChildAt(min);
      parent.insert(b, i);
      parent.insert(a, min);
      // MutableTreeNode node = (MutableTreeNode) parent.getChildAt(min);
      // parent.insert(node, i);
      // COMPARE_COUNTER++;
    }
  }
}
 
Example 12
Source Project: consulo   Source File: GroupNode.java    License: Apache License 2.0 5 votes vote down vote up
int removeUsagesBulk(@Nonnull Set<UsageNode> usages, @Nonnull DefaultTreeModel treeModel) {
  ApplicationManager.getApplication().assertIsDispatchThread();
  int removed = 0;
  synchronized (this) {
    List<MutableTreeNode> removedNodes = new SmartList<>();
    for (UsageNode usage : usages) {
      if (myChildren.remove(usage)) {
        removedNodes.add(usage);
        removed++;
      }
    }

    if (removed == 0) {
      for (GroupNode groupNode : getSubGroups()) {
        int delta = groupNode.removeUsagesBulk(usages, treeModel);
        if (delta > 0) {
          if (groupNode.getRecursiveUsageCount() == 0) {
            myChildren.remove(groupNode);
            removedNodes.add(groupNode);
          }
          removed += delta;
          if (removed == usages.size()) break;
        }
      }
    }
    if (!myChildren.isEmpty()) {
      removeNodesFromParent(treeModel, this, removedNodes);
    }
  }

  if (removed > 0) {
    myRecursiveUsageCount -= removed;
    if (myRecursiveUsageCount != 0) {
      treeModel.nodeChanged(this);
    }
  }

  return removed;
}
 
Example 13
Source Project: cstc   Source File: OperationsTree.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void removeNode(TreeNode selNode) {
   if (selNode == null) {
   	return;
   }
   
   MutableTreeNode parent = (MutableTreeNode) (selNode.getParent());
   if (parent == null) {
   	return;
   }
   
   if (selNode.getChildCount() == 0) {
    this.model.removeNodeFromParent((MutableTreeNode) selNode);	    	
   }
}
 
Example 14
Source Project: marathonv5   Source File: DynamicTree.java    License: Apache License 2.0 5 votes vote down vote up
/** Remove the currently selected node. */
public void removeCurrentNode() {
    TreePath currentSelection = tree.getSelectionPath();
    if (currentSelection != null) {
        DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode) (currentSelection.getLastPathComponent());
        MutableTreeNode parent = (MutableTreeNode) (currentNode.getParent());
        if (parent != null) {
            treeModel.removeNodeFromParent(currentNode);
            return;
        }
    }

    // Either there was no selection, or the root was selected.
    toolkit.beep();
}
 
Example 15
Source Project: netbeans   Source File: PathsCustomizer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void intervalAdded(ListDataEvent e) {
    for (int i = e.getIndex1(); i >= e.getIndex0(); i--) {
        Object obj = listModel.getElementAt(i);
        if (obj instanceof ClassPathSupport.Item) {
            DefaultMutableTreeNode node = toTreeNode(obj);
            treeModel.insertNodeInto(node, (MutableTreeNode)treeModel.getRoot(), e.getIndex0());
            TreePath path = new TreePath(node.getPath());
            tree.setSelectionPath(path);
            tree.makeVisible(path);
        }
    }
}
 
Example 16
@Override
public void keyRemoved(MapEvent<String, Integer> e)
{
	int index = types.indexOf(e.getKey());
	types.remove(index);
	removeNodeFromParent((MutableTreeNode) getChildAt(index));
}
 
Example 17
@Override
public void elementModified(ListEvent<AbilityFacade> e)
{
	//Logging.errorPrint("Modifying " + category + " - " + e.getElement());
	MutableTreeNode oldNode = (MutableTreeNode) getChildAt(e.getIndex());
	DefaultTreeTableNode node = buildAbilityNode(e.getElement());
	node.setUserObject(e.getElement());
	insertNodeInto(node, this, e.getIndex());
	removeNodeFromParent(oldNode);
}
 
Example 18
Source Project: weblaf   Source File: WebTreeModel.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void insertNodeInto ( @NotNull final MutableTreeNode child, @NotNull final MutableTreeNode parent, final int index )
{
    // Inserting node
    parent.insert ( child, index );

    // Firing node addition
    nodesWereInserted ( parent, new int[]{ index } );
}
 
Example 19
Source Project: netbeans   Source File: ConstructorPanel.java    License: Apache License 2.0 5 votes vote down vote up
protected MutableTreeNode getRootNode() {
    CheckNode root = new CheckNode.CGSClassNode(className);
    for (Property property : properties) {
        root.add(new CheckNode.CGSPropertyNode(property));
    }
    return root;
}
 
Example 20
Source Project: mts   Source File: ModelTreeRTStats.java    License: GNU General Public License v3.0 5 votes vote down vote up
public ModelTreeRTStats(MutableTreeNode root) {
    // We call constructor of DefaultTreeModel
    super(root);

    // Take instance of this ModelTree
    instance = this;

    // We create the ArrayList
    nodesSectionsList = new ArrayList();

    initColorMap();

    // We generate the tree
    generateTree();
}
 
Example 21
Source Project: evosql   Source File: DatabaseManagerSwing.java    License: Apache License 2.0 5 votes vote down vote up
private DefaultMutableTreeNode makeNode(Object userObject,
        MutableTreeNode parent) {

    DefaultMutableTreeNode node = new DefaultMutableTreeNode(userObject);

    if (parent != null) {
        treeModel.insertNodeInto(node, parent, parent.getChildCount());
    }

    return node;
}
 
Example 22
Source Project: CodeGen   Source File: BaseTemplateAction.java    License: MIT License 5 votes vote down vote up
/**
 * 直接通过model来添加新节点,则无需通过调用JTree的updateUI方法
 * model.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());
 * 直接通过节点添加新节点,则需要调用tree的updateUI方法
 */
private void addNode(DefaultMutableTreeNode pNode, MutableTreeNode newNode){
    pNode.add(newNode);
    //--------下面代码实现显示新节点(自动展开父节点)-------
    DefaultTreeModel model = (DefaultTreeModel) this.templateTree.getModel();
    TreeNode[] nodes = model.getPathToRoot(newNode);
    TreePath path = new TreePath(nodes);
    this.templateTree.scrollPathToVisible(path);
    this.templateTree.updateUI();
}
 
Example 23
Source Project: PolyGlot   Source File: FamTreeNode.java    License: MIT License 5 votes vote down vote up
@Override
public void insert(MutableTreeNode child, int index) {
    // only modify node if new. ID = 0 indicates loading from existing tree
    if (((FamTreeNode) child).famNode.getId() == 1) {
        famNode.addNode(((FamTreeNode) child).famNode);
        
        // once read, this is no longer a new node
        ((FamTreeNode) child).famNode.setId(0);
    }

    super.insert(child, index);
}
 
Example 24
Source Project: pumpernickel   Source File: DecoratedDemo.java    License: MIT License 5 votes vote down vote up
@Override
void addElement(String elementName) {
	final MutableTreeNode node;
	if (NAME_DELETABLE.equals(elementName)) {
		node = closeable;
	} else if (NAME_PLAYABLE.equals(elementName)) {
		node = playable;
	} else if (NAME_RATEABLE.equals(elementName)) {
		node = rateable;
	} else if (NAME_WARNING.equals(elementName)) {
		node = warning;
	} else {
		throw new IllegalArgumentException("Unrecognized name \""
				+ elementName + "\"");
	}
	Runnable r = new Runnable() {
		public void run() {
			treeModel.insertNodeInto(node, root, root.getChildCount());
			getDecoratedComponent().expandRow(0);
		}
	};
	if (SwingUtilities.isEventDispatchThread()) {
		r.run();
	} else {
		SwingUtilities.invokeLater(r);
	}
}
 
Example 25
Source Project: SNT   Source File: PathWindow.java    License: GNU General Public License v3.0 5 votes vote down vote up
protected void setSelectedPaths(final HelpfulJTree tree, final TreeModel model, final MutableTreeNode node,
		final HashSet<Path> set) {
	assert SwingUtilities.isEventDispatchThread();
	final int count = model.getChildCount(node);
	for (int i = 0; i < count; i++) {
		final DefaultMutableTreeNode child = (DefaultMutableTreeNode) model.getChild(node, i);
		final Path p = (Path) child.getUserObject();
		if (set.contains(p)) {
			tree.setSelected(child.getPath());
		}
		if (!model.isLeaf(child))
			setSelectedPaths(tree, model, child, set);
	}
}
 
Example 26
private MutableTreeNode createIndexesNode(DataSourceMetadata dataSourceMetadata, DataSourceApi dataSourceApi) {
    List<Map<String, String>> indexesMetadata =
            dataSourceMetadata.getMetadata(Neo4jBoltCypherDataSourceMetadata.INDEXES);
    PatchedDefaultMutableTreeNode indexTreeNode = new PatchedDefaultMutableTreeNode(
            new MetadataTreeNodeModel(INDEXES,
                    dataSourceApi,
                    String.format(INDEXES_TITLE, indexesMetadata.size()),
                    GraphIcons.Nodes.INDEX));
    indexesMetadata
            .forEach(row -> indexTreeNode.add(of(new MetadataTreeNodeModel(INDEX, dataSourceApi,
                    row.get("description").substring(6) + " " + row.get("state")))));

    return indexTreeNode;
}
 
Example 27
private MutableTreeNode createConstraintsNode(DataSourceMetadata dataSourceMetadata, DataSourceApi dataSourceApi) {
    List<Map<String, String>> constraintsMetadata =
            dataSourceMetadata.getMetadata(Neo4jBoltCypherDataSourceMetadata.CONSTRAINTS);
    PatchedDefaultMutableTreeNode indexTreeNode = new PatchedDefaultMutableTreeNode(
            new MetadataTreeNodeModel(CONSTRAINTS, dataSourceApi,
                    String.format(CONSTRAINTS_TITLE, constraintsMetadata.size()), GraphIcons.Nodes.CONSTRAINT));
    constraintsMetadata
            .forEach(row ->
                    indexTreeNode.add(of(new MetadataTreeNodeModel(CONSTRAINT, dataSourceApi,
                            row.get("description").substring(11)))));

    return indexTreeNode;
}
 
Example 28
private ListTreeTableModelOnColumns createModel(GraphQueryPlan plan, boolean isProfilePlan) {
    MutableTreeNode rootNode = new DefaultMutableTreeNode(plan);
    addChildrenPlansToModel(plan, rootNode);

    return new ListTreeTableModelOnColumns(rootNode,
            isProfilePlan ? getProfileQueryPlanColumns() : getQueryPlanColumns());
}
 
Example 29
private void addChildrenPlansToModel(GraphQueryPlan plan, MutableTreeNode node) {
    plan.children()
            .forEach(p -> {
                MutableTreeNode childNode = new DefaultMutableTreeNode(p);
                node.insert(childNode, 0);
                childNode.setParent(node);
                addChildrenPlansToModel(p, childNode);
            });
}
 
Example 30
Source Project: weblaf   Source File: AsyncTreeModel.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Inserts new child node into parent node at the specified index.
 *
 * @param child  new child node
 * @param parent parent node
 * @param index  insert index
 */
@Override
public void insertNodeInto ( @NotNull final MutableTreeNode child, @NotNull final MutableTreeNode parent, final int index )
{
    // Event Dispatch Thread check
    WebLookAndFeel.checkEventDispatchThread ();

    // Ensure model is installed
    checkInstalled ();

    final N parentNode = ( N ) parent;
    final N childNode = ( N ) child;

    // Ensure node children are loaded
    if ( parentNode.isLoaded () )
    {
        // Inserting new raw children
        List<N> cachedChildren = rawNodeChildrenCache.get ( parentNode.getId () );
        if ( cachedChildren == null )
        {
            cachedChildren = new ArrayList<N> ( 1 );
            rawNodeChildrenCache.put ( parentNode.getId (), cachedChildren );
        }
        cachedChildren.add ( index, childNode );
        cacheNodeById ( childNode );

        // Clearing node cache
        // That might be required in case nodes were moved inside of the tree
        clearNodeChildrenCache ( childNode, false );

        // Inserting node
        insertNodeIntoImpl ( childNode, parentNode, index );

        // Updating parent node sorting and filtering
        filterAndSort ( parentNode, false );
    }
}