javax.swing.tree.TreeNode Java Examples

The following examples show how to use javax.swing.tree.TreeNode. 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: MainView.java    From HiJson with Apache License 2.0 6 votes vote down vote up
private TreePath expandTreeNode(JTree tree,TreeNode[] arr, Boolean expand) {
    TreePath[] tp = new TreePath[arr.length];
    tp[0] = new TreePath(arr[0]);
    int pos = 0;
    for (int i = 1; i < arr.length; i++) {
        tp[i] = tp[i - 1].pathByAddingChild(arr[i]);
    }
    for (int i = 0; i < arr.length; i++) {
        if (expand) {
            tree.expandPath(tp[i]);
        } else {
            tree.collapsePath(tp[i]);
        }
        pos = i;
    }
    return tp[pos];
}
 
Example #2
Source File: TreeUtils.java    From weblaf with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns whether or not {@code anotherNode} is an ancestor of {@code node}.
 * If {@code anotherNode} is {@code null}, this method returns {@code false}.
 * Note that any node is considered as an ancestor of itself.
 * This operation is at worst O(h) where h is the distance from the root to {@code node}.
 *
 * @param node        tested {@code node}
 * @param anotherNode node to test as an ancestor of {@code node}
 * @return {@code true} if {@code anotherNode} is an ancestor of {@code node}, {@code false} otherwise
 */
public static boolean isNodeAncestor ( @NotNull final TreeNode node, @Nullable final TreeNode anotherNode )
{
    boolean nodeAncestor = false;
    if ( anotherNode != null )
    {
        TreeNode ancestor = node;
        do
        {
            if ( ancestor == anotherNode )
            {
                nodeAncestor = true;
                break;
            }
        }
        while ( ( ancestor = ancestor.getParent () ) != null );
    }
    return nodeAncestor;
}
 
Example #3
Source File: JCheckBoxTree.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 6 votes vote down vote up
private void resetCheckingState() {
    nodesCheckingState = new HashMap<>();
    checkedPaths = new ArrayList<TreePath>() {
        @Override
        public boolean add(TreePath e) {
            if (!contains(e)) {
                return super.add(e);
            }
            return false;
        }

    };
    if (getModel() == null) {
        return;
    }
    TreeNode node = (TreeNode) getModel().getRoot();
    if (node == null) {
        return;
    }
    addSubtreeToCheckingStateTracking(node);
}
 
Example #4
Source File: JDBCTreeTableView.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
protected SearchUtils.TreeHelper getSearchHelper() {
    return new SearchUtils.TreeHelper() {
        public int getNodeType(TreeNode tnode) {
            PresoObjAllocCCTNode node = (PresoObjAllocCCTNode)tnode;
            CCTNode parent = node.getParent();
            if (parent == null) return SearchUtils.TreeHelper.NODE_SKIP_DOWN; // invisible root
            
            if (isSQL(node)) {
                if (searchQueries) {
                    return searchCallerMethods ? SearchUtils.TreeHelper.NODE_SEARCH_DOWN :
                                                 SearchUtils.TreeHelper.NODE_SEARCH_NEXT;
                } else {
                    return searchCallerMethods ? SearchUtils.TreeHelper.NODE_SKIP_DOWN :
                                                 SearchUtils.TreeHelper.NODE_SKIP_NEXT;
                }
            }
            
            return searchCallerMethods ?
                   SearchUtils.TreeHelper.NODE_SEARCH_DOWN :
                   SearchUtils.TreeHelper.NODE_SKIP_NEXT;
        }
    };
}
 
Example #5
Source File: PlotConfigurationTreeModel.java    From rapidminer-studio with GNU Affero General Public License v3.0 6 votes vote down vote up
private void valueSourceAdded(int index, ValueSource valueSource, RangeAxisConfig source) {
	RangeAxisConfigTreeNode rangeAxisNode = getRangeAxisTreeNode(source);

	if (rangeAxisNode != null) {
		TreeNode child = rangeAxisNode.getChild(valueSource);
		if (child != null) {
			return; // already added..
		}

		// create new value source tree node
		ValueSourceTreeNode newChild = new ValueSourceTreeNode(valueSource);

		// add new tree node
		insertNodeInto(newChild, rangeAxisNode, index);

		// change selection path
		TreePath path = new TreePath(getPathToRoot(newChild));
		makeVisibleAndSelect(path);
	} else {
		throw new RuntimeException("RangeAxisConfig source is not present in TreeModel. This should not happen.");
	}
}
 
Example #6
Source File: ExplorerModelBuilder.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
private void updateContainer(TreeNode node) {
    // Save selection
    Set<DataSource> selectedDataSources = ExplorerSupport.sharedInstance().
                                          getSelectedDataSources();
    
    // Save expanded nodes
    Set<DataSource> expandedDataSources = ExplorerSupport.sharedInstance().
                                          getExpandedDataSources(((ExplorerNode)node).getUserObject());

    explorerModel.nodeStructureChanged(node);

    // Try to restore expanded nodes
    ExplorerSupport.sharedInstance().expandDataSources(expandedDataSources);
    
    // Try to restore selection
    ExplorerSupport.sharedInstance().selectDataSources(selectedDataSources);
}
 
Example #7
Source File: DSWorkbenchSelectionFrame.java    From dsworkbench with Apache License 2.0 6 votes vote down vote up
private TreePath find2(JTree tree, TreePath parent, Village pNode, int depth) {
    TreeNode node = (TreeNode) parent.getLastPathComponent();
    DefaultMutableTreeNode o = (DefaultMutableTreeNode) node;

    // If equal, go down the branch
    if (o.getUserObject().equals(pNode)) {
        // If at end, return match
        return parent;
    } else {
        // Traverse children
        if (node.getChildCount() >= 0) {
            for (Enumeration e = node.children(); e.hasMoreElements();) {
                TreeNode n = (TreeNode) e.nextElement();
                TreePath path = parent.pathByAddingChild(n);
                TreePath result = find2(tree, path, pNode, depth + 1);
                // Found a match
                if (result != null) {
                    return result;
                }
            }
        }
    }
    // No match at this branch
    return null;
}
 
Example #8
Source File: ElementTreePanel.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Invoke this method after you've changed how node is to be
 * represented in the tree.
 */
@Override
public void nodeChanged(TreeNode node) {
    if (listenerList != null && node != null) {
        TreeNode parent = node.getParent();

        if (parent == null && node != root) {
            parent = root;
        }
        if (parent != null) {
            int anIndex = getIndexOfChild(parent, node);

            if (anIndex != -1) {
                int[] cIndexs = new int[1];

                cIndexs[0] = anIndex;
                nodesChanged(parent, cIndexs);
            }
        }
    }
}
 
Example #9
Source File: CProjectTreeModel.java    From binnavi with Apache License 2.0 6 votes vote down vote up
@Override
public void nodeStructureChanged(final TreeNode node) {
  // ensures the reconstruction of the nodes expansion state (which gets normally lost - which
  // means that the nodes collapse)
  final Enumeration<TreePath> expandedPaths =
      m_tree.getExpandedDescendants(new TreePath(getRoot()));

  super.nodeStructureChanged(node);

  if (expandedPaths != null) {
    while (expandedPaths.hasMoreElements()) {
      final TreePath path = expandedPaths.nextElement();
      m_tree.expandPath(path);
    }
  }

  m_tree.validate();
}
 
Example #10
Source File: AssertionTreeNode.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
public TreeNode getChildAt_internal(int index) {
    if (object instanceof List) {
        return getNodeForList((List<?>) object, index);
    }
    if (object instanceof Map) {
        return getNodeForMap((Map<?, ?>) object, index);
    }
    Method method;
    if (object instanceof RComponent) {
        Method o = ((RComponent) object).getMethods().get(index);
        method = o;
    } else {
        method = getMethods(object).get(index);
    }
    return getNodeForMethod(method);
}
 
Example #11
Source File: ElementTreePanel.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Invoke this method after you've changed how node is to be
 * represented in the tree.
 */
@Override
public void nodeChanged(TreeNode node) {
    if (listenerList != null && node != null) {
        TreeNode parent = node.getParent();

        if (parent == null && node != root) {
            parent = root;
        }
        if (parent != null) {
            int anIndex = getIndexOfChild(parent, node);

            if (anIndex != -1) {
                int[] cIndexs = new int[1];

                cIndexs[0] = anIndex;
                nodesChanged(parent, cIndexs);
            }
        }
    }
}
 
Example #12
Source File: PropertyEditableColumnDropdown.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * @see IColumn#newCell(MarkupContainer, String, TreeNode, int)
 */
public Component newCell(MarkupContainer parent, String id, TreeNode node, int level)
{
	if(!((NodeModel) ((DefaultMutableTreeNode) node).getUserObject()).isNodeEditable()){
		return new EditablePanelEmpty(id);
	}
	
	if(DelegatedAccessConstants.TYPE_ACCESS_SHOPPING_PERIOD_USER == type){
		if(!((NodeModel) ((DefaultMutableTreeNode) node).getUserObject()).getNodeShoppingPeriodAdmin()){
			return new EditablePanelEmpty(id);
		}
	}
	
	if(((NodeModel) ((DefaultMutableTreeNode) node).getUserObject()).isDirectAccess()){
		return new EditablePanelDropdown(id, new PropertyModel(node, getPropertyExpression()), (NodeModel) ((DefaultMutableTreeNode) node).getUserObject(), node, roleMap, type, subAdminRoles);
	}else{
		return new EditablePanelDropdownText(id, new PropertyModel(node, getPropertyExpression()), (NodeModel) ((DefaultMutableTreeNode) node).getUserObject(), node, roleMap, type);
	}
}
 
Example #13
Source File: VisualizerNodeEventsOrderTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testForToStrictAssertsInVisualizerChildren() throws InterruptedException, InvocationTargetException {
    // block AWT thread
    Block b = new Block();
    b.block();
    Node n = lch.getNodeAt(0);
    final TreeNode tn = Visualizer.findVisualizer(n);
    SwingUtilities.invokeLater(new Runnable() {

        public void run() {
            try {
                int idx = ta.getIndex(tn);
            } catch (Throwable ex) {
                e = ex;
            }
        }
    });
    lch.keys("x", "y", "y");
    b.unblock();
    waitForAwtQueue();
    if (e != null) {
        fail();
    }
}
 
Example #14
Source File: XTree.java    From scelight with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link XTree}.
 * 
 * @param root root node
 */
public XTree( final TreeNode root ) {
	super( root );
	
	ToolTipManager.sharedInstance().registerComponent( this );
	
	getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION );
	
	// Tree nodes are rendered by the tree cell renderer, they do not fill the whole row.
	// Make the whole row clickable (to select/deselect the row's node):
	addMouseListener( new MouseAdapter() {
		@Override
		public void mousePressed( final MouseEvent event ) {
			int row = getRowForLocation( event.getX(), event.getY() );
			if ( row >= 0 )
				return; // Exact click on a node, default behavior is good
				
			row = getRowForEventExtended( event );
			if ( row < 0 )
				return;
			
			if ( isRowSelected( row ) ) {
				if ( event.isControlDown() )
					clearSelection();
			} else
				setSelectionRow( row );
		}
	} );
}
 
Example #15
Source File: LivenessTreeTableView.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void setValueAt(Object aValue, TreeNode node, int columnIndex) {
    if (selection == null) columnIndex++;
    
    if (columnIndex == 0) {
        if (Boolean.TRUE.equals(aValue)) selection.add(nodesMap.get(node));
        else selection.remove(nodesMap.get(node));
    }
}
 
Example #16
Source File: ProfilerTreeTable.java    From visualvm with GNU General Public License v2.0 5 votes vote down vote up
TreePathKey(TreeNode[] _pathToRoot) {
            pathToRoot = _pathToRoot;
            
            hashCode = 1;
            for (TreeNode node : pathToRoot)
                hashCode = 31 * hashCode + node.hashCode();
            
//            hashCode = Arrays.deepHashCode(pathToRoot);
        }
 
Example #17
Source File: AbstractTab.java    From DiskBrowser with GNU General Public License v3.0 5 votes vote down vote up
protected TreePath getPathToNode (DefaultMutableTreeNode selectNode)
// ---------------------------------------------------------------------------------//
{
  DefaultTreeModel treeModel = (DefaultTreeModel) tree.getModel ();
  TreeNode[] nodes = treeModel.getPathToRoot (selectNode);
  if (nodes == null)
    return null;
  return new TreePath (nodes);
}
 
Example #18
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
@Override protected TreeNode doInBackground() throws InterruptedException {
  int current = 0;
  while (current <= lengthOfTask && !isCancelled()) {
    doSomething();
    publish(100 * current++ / lengthOfTask);
  }
  return treeNode;
}
 
Example #19
Source File: CommitNode.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void render(@Nonnull ColoredTreeCellRenderer renderer) {
  renderer.append("   ");
  TreeNode parent = getParent();
  new IssueLinkRenderer(myProject, renderer).appendTextWithLinks(getUserObject().getSubject(), PushLogTreeUtil
    .addTransparencyIfNeeded(SimpleTextAttributes.REGULAR_ATTRIBUTES,
                             !(parent instanceof RepositoryNode) || ((RepositoryNode)parent).isChecked()));
}
 
Example #20
Source File: ListTreeTableModelOnColumns.java    From consulo with Apache License 2.0 5 votes vote down vote up
public List getItems() {
  ArrayList result = new ArrayList();
  TreeNode root = (TreeNode) getRoot();
  for (int i = 0; i < root.getChildCount(); i++) {
    addElementsToCollection(root.getChildAt(i), result);
  }
  return result;
}
 
Example #21
Source File: ImageORPage.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 5 votes vote down vote up
@JsonIgnore
@Override
public TreeNode getChildAt(int i) {
    if (objectGroups.get(i).getChildCount() > 1) {
        return objectGroups.get(i);
    }
    return objectGroups.get(i).getChildAt(0);
}
 
Example #22
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
private static void searchTree(JTree tree, TreePath path, String q) {
  Object o = path.getLastPathComponent();
  if (o instanceof TreeNode) {
    TreeNode node = (TreeNode) o;
    if (Objects.toString(node).startsWith(q)) {
      tree.expandPath(path.getParentPath());
    }
    if (!node.isLeaf()) {
      // Java 9: Collections.list(node.children())
      Collections.list((Enumeration<?>) node.children())
          .forEach(n -> searchTree(tree, path.pathByAddingChild(n), q));
    }
  }
}
 
Example #23
Source File: WebTreeModel.java    From weblaf with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Forces update of all visible node sizes and view.
 * This call might be useful if renderer changes dramatically and you have to update the whole tree.
 */
public void updateTree ()
{
    final N rootNode = getRoot ();
    if ( rootNode != null )
    {
        final TreeNode[] path = TreeUtils.getPath ( rootNode );
        fireTreeStructureChanged ( WebTreeModel.this, path, null, null );
    }
}
 
Example #24
Source File: NodeFileOrFolder.java    From netbeans-mmd-plugin with Apache License 2.0 5 votes vote down vote up
@Nonnull
public TreePath makeTreePath() {
  final List<Object> path = new ArrayList<>();
  TreeNode node = this;
  while (node != null) {
    path.add(0, node);
    node = node.getParent();
  }
  return new TreePath(path.toArray());
}
 
Example #25
Source File: XDebuggerTreeSpeedSearch.java    From consulo with Apache License 2.0 5 votes vote down vote up
private TreePath findInChildren(TreeNode node, String string) {
  if (node.isLeaf() || !(node instanceof XDebuggerTreeNode)) {
    return null;
  }

  LinkedList<XDebuggerTreeNode> queue = new LinkedList<XDebuggerTreeNode>();
  queue.addLast((XDebuggerTreeNode)node);

  int initialLevel = ((XDebuggerTreeNode)node).getPath().getPathCount();

  while (!queue.isEmpty()) {
    XDebuggerTreeNode p = queue.removeFirst();

    if ((p.getPath().getPathCount() - initialLevel) > 3) {
      return null;
    }

    List<? extends TreeNode> children = p.getChildren();
    if (children.isEmpty()) {
      continue;
    }

    for (TreeNode child : children) {
      if (!(child instanceof XDebuggerTreeNode)) {
        continue;
      }

      TreePath result = match(child, string);
      if (result != null) {
        return result;
      }

      if (!child.isLeaf()) {
        queue.addLast((XDebuggerTreeNode)child);
      }
    }
  }

  return null;
}
 
Example #26
Source File: Test4631471.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void main() throws Exception {
    // the DefaultMutableTreeNode will archive correctly
    new Test4631471() {
        protected Object getObject() {
            return getRoot();
        }
    }.test(false);

    // the DefaultTreeModel will also archive correctly
    new Test4631471() {
        protected Object getObject() {
            return getModel();
        }
    }.test(false);

    // create a new model from the root node
    // this simulates the the MetaData ctor:
    // registerConstructor("javax.swing.tree.DefaultTreeModel", new String[]{"root"});
    new Test4631471() {
        protected Object getObject() {
            return new DefaultTreeModel((TreeNode) getModel().getRoot());
        }
    }.test(false);

    // the JTree will archive correctly too
    new Test4631471() {
        protected Object getObject() {
            return getTree();
        }
    }.test(false);
}
 
Example #27
Source File: ProfilerTreeTable.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private SortedFilteredTreeModel treeModelImpl(TreeNode root, Comparator comparator, RowFilter filter) {
    return new SortedFilteredTreeModel(root, tree == null ? null : tree.getCellRenderer(), comparator, filter) {
        protected void fireTreeStructureChanged(Object source, Object[] path,
                                int[] childIndices,
                                Object[] children) {
            UIState uiState = tree == null ? null : getUIState(tree);
            super.fireTreeStructureChanged(source, path, childIndices, children);
            if (uiState != null) restoreExpandedNodes(tree, uiState);
            fireTableDataChanged(); // Clears selection
            if (uiState != null) restoreSelectedNodes(tree, uiState);
        }
    };
}
 
Example #28
Source File: LocationTreePaneUI.java    From pumpernickel with MIT License 5 votes vote down vote up
private static TreeNode createRootNode(IOLocation[] rootLocations) {
	DefaultMutableTreeNode root = new DefaultMutableTreeNode();
	for (IOLocation loc : rootLocations) {
		DefaultMutableTreeNode node = new DefaultMutableTreeNode(loc);
		root.add(node);
	}
	return root;
}
 
Example #29
Source File: HintsPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public HintMetadata getSelectedHint() {
        TreePath selectionPath = errorTree.getSelectionModel().getSelectionPath();
        if (selectionPath==null) {
            return null;
}
        DefaultMutableTreeNode lastPathComponent = (DefaultMutableTreeNode) (MutableTreeNode) (TreeNode) selectionPath.getLastPathComponent();
        if (lastPathComponent!= null && lastPathComponent.getUserObject() instanceof HintMetadata)
            return (HintMetadata) lastPathComponent.getUserObject();
        return null;
    }
 
Example #30
Source File: JFrameRTStats.java    From mts with GNU General Public License v3.0 5 votes vote down vote up
public static void expandAll(JTree tree)
{
    // Catch root of the tree
    TreeNode root = (TreeNode)tree.getModel().getRoot();
    
    // Traverse Tree from Root
    expandAll(tree, new TreePath(root));
}