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

The following examples show how to use javax.swing.tree.DefaultMutableTreeNode#getChildCount() . 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: MainPanel.java    From java-swing-tips with MIT License 6 votes vote down vote up
@Override public boolean importData(TransferHandler.TransferSupport support) {
  DefaultMutableTreeNode[] nodes;
  try {
    Transferable t = support.getTransferable();
    nodes = (DefaultMutableTreeNode[]) t.getTransferData(FLAVOR);
  } catch (UnsupportedFlavorException | IOException ex) {
    return false;
  }
  TransferHandler.DropLocation tdl = support.getDropLocation();
  if (tdl instanceof JTree.DropLocation) {
    JTree.DropLocation dl = (JTree.DropLocation) tdl;
    int childIndex = dl.getChildIndex();
    TreePath dest = dl.getPath();
    DefaultMutableTreeNode parent = (DefaultMutableTreeNode) dest.getLastPathComponent();
    JTree tree = (JTree) support.getComponent();
    DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
    AtomicInteger idx = new AtomicInteger(childIndex < 0 ? parent.getChildCount() : childIndex);
    Stream.of(nodes).forEach(node -> {
      DefaultMutableTreeNode clone = new DefaultMutableTreeNode(node.getUserObject());
      model.insertNodeInto(deepCopyTreeNode(node, clone), parent, idx.incrementAndGet());
    });
    return true;
  }
  return false;
}
 
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: ProjectTree.java    From TrakEM2 with GNU General Public License v3.0 6 votes vote down vote up
/** Move up (-1) or down (1). */
private void move(final DefaultMutableTreeNode node, final int direction) {
	final ProjectThing pt = (ProjectThing)node.getUserObject();
	if (null == pt) return;
	// Move: within the list of children of the parent ProjectThing:
	if (!pt.move(direction)) return;
	// If moved, reposition within the list of children
	final DefaultMutableTreeNode parent_node = (DefaultMutableTreeNode)node.getParent();
	int index = parent_node.getChildCount() -1;
	((DefaultTreeModel)this.getModel()).removeNodeFromParent(node);
	index = pt.getParent().getChildren().indexOf(pt);
	((DefaultTreeModel)this.getModel()).insertNodeInto(node, parent_node, index);
	// restore selection path
	final TreePath trp = new TreePath(node.getPath());
	this.scrollPathToVisible(trp);
	this.setSelectionPath(trp);
	this.updateUILater();
}
 
Example 4
Source File: InspectorPanel.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void maybePopulateChildren(DefaultMutableTreeNode treeNode) {
  final Object userObject = treeNode.getUserObject();
  if (userObject instanceof DiagnosticsNode) {
    final DiagnosticsNode diagnostic = (DiagnosticsNode)userObject;
    if (diagnostic.hasChildren() && treeNode.getChildCount() == 0) {
      diagnostic.safeWhenComplete(diagnostic.getChildren(), (ArrayList<DiagnosticsNode> children, Throwable throwable) -> {
        if (throwable != null) {
          FlutterUtils.warn(LOG, throwable);
          return;
        }
        if (treeNode.getChildCount() == 0) {
          setupChildren(diagnostic, treeNode, children, true);
        }
        getTreeModel().nodeStructureChanged(treeNode);
        if (treeNode == selectedNode) {
          myRootsTree.expandPath(new TreePath(treeNode.getPath()));
        }
      });
    }
  }
}
 
Example 5
Source File: BaseTreePage.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * This is a helper function for updateNodeAccess
 * 
 * @param node
 * @param userId
 * @param defaultRole
 */
private void updateNodeAccessHelper(DefaultMutableTreeNode node, String userId, String[] defaultRole){
	if(node.getUserObject() != null){
		NodeModel nodeModel = (NodeModel) node.getUserObject();
		if(defaultRole != null && defaultRole.length == 2){
			nodeModel.setRealm(defaultRole[0]);
			nodeModel.setRole(defaultRole[1]);
		}
		if(nodeModel.isModified()){
			//since this is the DA UI, we need to set instructorEdit to false
			((NodeModel) node.getUserObject()).setInstructorEdited(false);
			projectLogic.updateNodePermissionsForUser(node, userId);
			//now reset the node's "original" values to ensure the next save will check against
			//the newly saved settings
			nodeModel.setOriginals();
		}

		//check the rest of the children:
		for(int i = 0; i < node.getChildCount(); i++){
			updateNodeAccessHelper((DefaultMutableTreeNode)node.getChildAt(i), userId, defaultRole);
		}
	}
}
 
Example 6
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 7
Source File: ViewManager.java    From leetcode-editor with Apache License 2.0 6 votes vote down vote up
public static void pick(JTree tree, JBScrollPane scrollPane) {

        DefaultTreeModel treeMode = (DefaultTreeModel) tree.getModel();
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) treeMode.getRoot();
        if (root.isLeaf()) {
            return;
        }
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) root.getChildAt(0);
        if (node.isLeaf()) {
            return;
        }
        int i = (int) (Math.random() * node.getChildCount());
        DefaultMutableTreeNode select = (DefaultMutableTreeNode) node.getChildAt(i);

        TreePath toShowPath = new TreePath(select.getPath());
        tree.setSelectionPath(toShowPath);
        Rectangle bounds = tree.getPathBounds(toShowPath);
        Point point = new Point(0, (int) bounds.getY());
        JViewport viewport = scrollPane.getViewport();
        viewport.setViewPosition(point);
        return;
    }
 
Example 8
Source File: MyTree.java    From myqq with MIT License 6 votes vote down vote up
/**
 * 删除树里面的某个好友
 */
public void deleteFriend(String groupName,String friendName)
{
	DefaultMutableTreeNode root=(DefaultMutableTreeNode) treeModel.getRoot();
	for(int i=0;i<root.getChildCount();i++)
	{
		if(root.getChildAt(i).toString().startsWith(groupName))
		{
			for(int j=0;j<root.getChildAt(i).getChildCount();j++)
			{
				if(root.getChildAt(i).getChildAt(j).toString().startsWith(friendName))
				{
					System.out.println(root.getChildAt(i).getChildAt(j));
					DefaultMutableTreeNode node=(DefaultMutableTreeNode)root.getChildAt(i).getChildAt(j);
					node.removeFromParent();
					System.out.println("删除成功!");
				}
				break;
			}
		}
		break;
	}
}
 
Example 9
Source File: CellRenderer.java    From Luyten with Apache License 2.0 6 votes vote down vote up
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf,
		int row, boolean hasFocus) {
	super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
	DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
	if (node.getChildCount() > 0) {
		setIcon(this.pack);
	} else if (getFileName(node).endsWith(".class") || getFileName(node).endsWith(".java")) {
		setIcon(this.java_image);
	} else if (getFileName(node).endsWith(".yml") || getFileName(node).endsWith(".yaml")) {
		setIcon(this.yml_image);
	} else {
		setIcon(this.file_image);
	}

	return this;
}
 
Example 10
Source File: BaseTreePage.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * This is a helper function for updateNodeAccess
 * 
 * @param node
 * @param userId
 * @param defaultRole
 */
private void updateNodeAccessHelper(DefaultMutableTreeNode node, String userId, String[] defaultRole){
	if(node.getUserObject() != null){
		NodeModel nodeModel = (NodeModel) node.getUserObject();
		if(defaultRole != null && defaultRole.length == 2){
			nodeModel.setRealm(defaultRole[0]);
			nodeModel.setRole(defaultRole[1]);
		}
		if(nodeModel.isModified()){
			//since this is the DA UI, we need to set instructorEdit to false
			((NodeModel) node.getUserObject()).setInstructorEdited(false);
			projectLogic.updateNodePermissionsForUser(node, userId);
			//now reset the node's "original" values to ensure the next save will check against
			//the newly saved settings
			nodeModel.setOriginals();
		}

		//check the rest of the children:
		for(int i = 0; i < node.getChildCount(); i++){
			updateNodeAccessHelper((DefaultMutableTreeNode)node.getChildAt(i), userId, defaultRole);
		}
	}
}
 
Example 11
Source File: ObjectTrees.java    From JglTF with MIT License 5 votes vote down vote up
/**
 * Recursively find the node that has a user object that is a 
 * {@link NodeEntry} with the given value
 * 
 * @param node The current node
 * @param nodeEntryValue The {@link NodeEntry} value
 * @param result The list that stores the result 
 */
private static void findNodesWithNodeEntryValue(
    DefaultMutableTreeNode node, Object nodeEntryValue, 
    List<DefaultMutableTreeNode> result)
{
    Object userObject = node.getUserObject();
    if (userObject instanceof NodeEntry)
    {
        NodeEntry nodeEntry = (NodeEntry)userObject;
        if (nodeEntry.getValue() == nodeEntryValue)
        {
            result.add(node);
        }
    }
    else
    {
        logger.warning(
            "Unexpected user object type: "+userObject.getClass());
    }
    int n = node.getChildCount();
    for (int i=0; i<n; i++)
    {
        TreeNode child = node.getChildAt(i);
        if (child instanceof DefaultMutableTreeNode)
        {
            DefaultMutableTreeNode childNode = 
                (DefaultMutableTreeNode)child;    
            findNodesWithNodeEntryValue(childNode, nodeEntryValue, result);
        }
        else
        {
            logger.warning("Unexpected node type: "+child.getClass());
        }
    }
}
 
Example 12
Source File: ProjectLogicImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private List<NodeModel> getSiteNodes(DefaultMutableTreeNode treeNode){
	List<NodeModel> returnList = new ArrayList<NodeModel>();
	if(treeNode != null){
		if(((NodeModel) treeNode.getUserObject()).getNode().title.startsWith("/site/")){
			returnList.add((NodeModel) treeNode.getUserObject());
		}
		//check the rest of the children:
		for(int i = 0; i < treeNode.getChildCount(); i++){
			returnList.addAll(getSiteNodes((DefaultMutableTreeNode)treeNode.getChildAt(i)));
		}
	}

	return returnList;
}
 
Example 13
Source File: NodeDataPanel.java    From JPPF with Apache License 2.0 5 votes vote down vote up
/**
 * Add the specified node to the specified driver in the treeTable.
 * @param driverData the driver to add to.
 * @param nodeData the node to add.
 */
private synchronized void addNode(final TopologyDriver driverData, final TopologyNode nodeData) {
  final DefaultMutableTreeNode nodeNode = TopologyUtils.addNode(model, driverData, nodeData);
  if (nodeNode != null) {
    final DefaultMutableTreeNode driverNode = (DefaultMutableTreeNode) nodeNode.getParent();
    //if ((driverNode.getChildCount() == 1) && !treeTable.isCollapsed(driverNode)) treeTable.expand(driverNode);
    if (driverNode.getChildCount() == 1) treeTable.expand(driverNode);
  }
}
 
Example 14
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
private static void sort3(DefaultMutableTreeNode parent) {
  // @SuppressWarnings("unchecked")
  // Enumeration<DefaultMutableTreeNode> e = parent.children();
  // ArrayList<DefaultMutableTreeNode> children = Collections.list(e);

  int n = parent.getChildCount();
  List<DefaultMutableTreeNode> children = new ArrayList<>(n);
  for (int i = 0; i < n; i++) {
    children.add((DefaultMutableTreeNode) parent.getChildAt(i));
  }

  children.sort(tnc);
  parent.removeAllChildren();
  children.forEach(parent::add);
}
 
Example 15
Source File: SelectNodesLink.java    From JPPF with Apache License 2.0 5 votes vote down vote up
@Override
protected void onClick(final AjaxRequestTarget target, final TableTreeData data) {
  final DefaultMutableTreeNode root = (DefaultMutableTreeNode) data.getModel().getRoot();
  final SelectionHandler handler = data.getSelectionHandler();
  handler.clearSelection();
  for (int i=0; i<root.getChildCount(); i++) {
    final DefaultMutableTreeNode dmtnDriver = (DefaultMutableTreeNode) root.getChildAt(i);
    for (int j=0; j<dmtnDriver.getChildCount(); j++) {
      final DefaultMutableTreeNode dmtnNode = (DefaultMutableTreeNode) dmtnDriver.getChildAt(j);
      final AbstractTopologyComponent node = (AbstractTopologyComponent) dmtnNode.getUserObject();
      if (node.isNode()) handler.select(node.getUuid());
    }
  }
}
 
Example 16
Source File: AbstractTreeViewPanel.java    From openAGV with Apache License 2.0 5 votes vote down vote up
@Override // TreeView
public void removeChildren(Object item) {
  DefaultMutableTreeNode node = findFirst(item);
  int size = node.getChildCount();

  for (int i = size - 1; i > -1; i--) {
    fTreeModel.removeNodeFromParent((DefaultMutableTreeNode) node.getChildAt(i));
  }
}
 
Example 17
Source File: Sorter.java    From jAudioGIT with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Takes the tree with the given root and reorders it so that all siblings are
 * sorted alphebetically. Recurses through the children so that each level is
 * sorted alphabetically. Returns the root of the new sorted tree.
 *
 * @param	root_unsorted_tree The root of the tree to be sorted.
 * @return	A copy of the tree that has been sorted.
 * @see		Collator
 * @see		DefaultMutableTreeNode
 */
public static DefaultMutableTreeNode sortTree(DefaultMutableTreeNode root_unsorted_tree)
{
	// Children of root_unsorted_tree
	DefaultMutableTreeNode children[] = new DefaultMutableTreeNode[root_unsorted_tree.getChildCount()];
	
	// Sort the children of root_unsorted_tree
	Collator string_comparer = Collator.getInstance();
	for (int i = 0; i < root_unsorted_tree.getChildCount(); i++)
		children[i] = (DefaultMutableTreeNode) root_unsorted_tree.getChildAt(i);
	for (int i = 0; i < root_unsorted_tree.getChildCount(); i++)
	{
		// Find if any nodes should come before children[i]
		DefaultMutableTreeNode first = children[i];
		String first_name = (String) first.getUserObject();
		int first_indice = i;
		for (int j = i + 1; j < children.length; j++)
		{
			String test_name = (String) children[j].getUserObject();
			if (string_comparer.compare(first_name, test_name) > 0)
			{
				first_name = test_name;
				first_indice = j;
			}
		}

		// Perform a switch if necessary
		if (first_indice != i)
		{
			DefaultMutableTreeNode temp = children[i];
			children[i] = children[first_indice];
			children[first_indice] = temp;
		}
	}

	// Sort the children of the children of root_unsorted_tree
	for (int i = 0; i < children.length; i++)
		if (!children[i].isLeaf())
			children[i] = sortTree(children[i]);

	// Return the sorted tree
	DefaultMutableTreeNode root_sorted_tree = new DefaultMutableTreeNode(root_unsorted_tree.getUserObject());
	for (int i = 0; i < children.length; i++)
		root_sorted_tree.add(children[i]);
	return root_sorted_tree;
}
 
Example 18
Source File: InspectorTreeUI.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected void paintVerticalPartOfLeg(final Graphics g, final Rectangle clipBounds, final Insets insets, final TreePath path) {
  final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
  if (node.getChildCount() < 2) {
    // We could draw lines for nodes with a single child but we omit them
    // to more of an emphasis of lines for nodes with multiple children.
    return;
  }
  final DiagnosticsNode diagnostic = maybeGetDiagnostic(node);
  if (diagnostic != null && !diagnostic.hasChildren()) {
    // This avoids drawing lines for nodes with only property children.
    return;
  }

  final int depth = path.getPathCount() - 1;
  if (depth == 0 && !getShowsRootHandles() && !isRootVisible()) {
    return;
  }

  int lineX = getRowX(-1, depth);
  if (leftToRight) {
    lineX = lineX - getRightChildIndent() + insets.left;
  }
  else {
    lineX = tree.getWidth() - lineX - insets.right +
            getRightChildIndent() - 1;
  }
  final int clipLeft = clipBounds.x;
  final int clipRight = clipBounds.x + (clipBounds.width - 1);

  if (lineX >= clipLeft && lineX <= clipRight) {
    final int clipTop = clipBounds.y;
    final int clipBottom = clipBounds.y + clipBounds.height;
    Rectangle parentBounds = getPathBounds(tree, path);
    boolean previousDashed = false;

    int top;
    if (parentBounds == null) {
      top = Math.max(insets.top + getVerticalLegBuffer(),
                     clipTop);
    }
    else {
      top = Math.max(parentBounds.y + parentBounds.height +
                     getVerticalLegBuffer(), clipTop);
    }

    if (depth == 0 && !isRootVisible()) {
      final TreeModel model = getModel();

      if (model != null) {
        final Object root = model.getRoot();

        if (model.getChildCount(root) > 0) {
          parentBounds = getPathBounds(tree, path.
            pathByAddingChild(model.getChild(root, 0)));
          if (parentBounds != null) {
            top = Math.max(insets.top + getVerticalLegBuffer(),
                           parentBounds.y +
                           parentBounds.height / 2);
          }
        }
      }
    }

    for (int i = 0; i < node.getChildCount(); ++i) {
      final DefaultMutableTreeNode child = (DefaultMutableTreeNode)node.getChildAt(i);
      final DiagnosticsNode childDiagnostic = maybeGetDiagnostic(child);
      boolean dashed = false;
      if (childDiagnostic != null) {
        dashed = childDiagnostic.getStyle() == DiagnosticsTreeStyle.offstage;
      }

      final Rectangle childBounds = getPathBounds(tree, path.pathByAddingChild(child));
      if (childBounds == null)
      // This shouldn't happen, but if the model is modified
      // in another thread it is possible for this to happen.
      // Swing isn't multithreaded, but I'll add this check in
      // anyway.
      {
        continue;
      }

      final int bottom = Math.min(childBounds.y +
                                  (childBounds.height / 2), clipBottom);

      if (top <= bottom && bottom >= clipTop && top <= clipBottom) {
        g.setColor(JBColor.GRAY);
        paintVerticalLine(g, tree, lineX, top, bottom, dashed);
      }
      top = bottom;
      previousDashed = dashed;
    }
  }
}
 
Example 19
Source File: InspectorPanel.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
boolean hasPlaceholderChildren(DefaultMutableTreeNode node) {
  return node.getChildCount() == 0 ||
         (node.getChildCount() == 1 && ((DefaultMutableTreeNode)node.getFirstChild()).getUserObject() instanceof String);
}
 
Example 20
Source File: MiscTools.java    From megabasterd with GNU General Public License v3.0 4 votes vote down vote up
private static void _sortTreeNode(DefaultMutableTreeNode parent) {

        int n = parent.getChildCount();

        List<DefaultMutableTreeNode> children = new ArrayList<>(n);

        for (int i = 0; i < n; i++) {

            children.add((DefaultMutableTreeNode) parent.getChildAt(i));
        }

        Collections.sort(children, TREE_NODE_COMPARATOR);

        parent.removeAllChildren();

        children.forEach((node) -> {
            parent.add(node);
        });
    }