类javax.swing.tree.TreeNode源码实例Demo

下面列出了怎么用javax.swing.tree.TreeNode的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: visualvm   文件: JDBCTreeTableView.java
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;
        }
    };
}
 
源代码2 项目: weblaf   文件: TreeUtils.java
/**
 * 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;
}
 
源代码3 项目: visualvm   文件: ExplorerModelBuilder.java
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);
}
 
源代码4 项目: dsworkbench   文件: DSWorkbenchSelectionFrame.java
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;
}
 
源代码5 项目: jdk8u-dev-jdk   文件: ElementTreePanel.java
/**
 * 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);
            }
        }
    }
}
 
源代码6 项目: binnavi   文件: CProjectTreeModel.java
@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();
}
 
源代码7 项目: marathonv5   文件: AssertionTreeNode.java
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);
}
 
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.");
	}
}
 
源代码9 项目: sakai   文件: PropertyEditableColumnDropdown.java
/**
 * @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);
	}
}
 
源代码10 项目: netbeans   文件: VisualizerNodeEventsOrderTest.java
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();
    }
}
 
源代码11 项目: HiJson   文件: MainView.java
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];
}
 
源代码12 项目: openjdk-jdk8u   文件: ElementTreePanel.java
/**
 * 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);
            }
        }
    }
}
 
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);
}
 
源代码14 项目: netbeans-mmd-plugin   文件: NodeFileOrFolder.java
@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());
}
 
源代码15 项目: java-swing-tips   文件: MainPanel.java
@Override protected TreeNode doInBackground() throws InterruptedException {
  int current = 0;
  while (current <= lengthOfTask && !isCancelled()) {
    doSomething();
    publish(100 * current++ / lengthOfTask);
  }
  return treeNode;
}
 
源代码16 项目: scelight   文件: XTree.java
/**
 * 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 );
		}
	} );
}
 
源代码17 项目: pumpernickel   文件: TreeKeyListener.java
@Override
protected boolean changeSelectionUsingText(KeyEvent e, String inputStr) {
	inputStr = inputStr.toUpperCase();
	JTree tree = (JTree) e.getComponent();

	int[] selection = tree.getSelectionRows();
	Arrays.sort(selection);
	int i = selection.length > 0 ? selection[selection.length - 1] : 0;
	int rowCount = tree.getRowCount();
	for (int offset = 0; offset < rowCount; offset++) {
		int row = (i + offset) % rowCount;
		TreePath path = tree.getPathForRow(row);
		TreeNode node = (TreeNode) path.getLastPathComponent();
		Component renderer = tree.getCellRenderer()
				.getTreeCellRendererComponent(tree, node, false,
						tree.isExpanded(path), node.isLeaf(), row,
						tree.isFocusOwner());
		String str = getText(renderer);
		if (str != null && str.length() >= 0
				&& str.toUpperCase().startsWith(inputStr)) {
			tree.setSelectionPath(path);
			return true;
		}
	}

	return false;
}
 
源代码18 项目: visualvm   文件: ProfilerTreeTable.java
TreePathKey(TreeNode[] _pathToRoot) {
            pathToRoot = _pathToRoot;
            
            hashCode = 1;
            for (TreeNode node : pathToRoot)
                hashCode = 31 * hashCode + node.hashCode();
            
//            hashCode = Arrays.deepHashCode(pathToRoot);
        }
 
源代码19 项目: mts   文件: JFrameRTStats.java
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));
}
 
源代码20 项目: consulo   文件: ListTreeTableModelOnColumns.java
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;
}
 
@JsonIgnore
@Override
public TreeNode getChildAt(int i) {
    if (objectGroups.get(i).getChildCount() > 1) {
        return objectGroups.get(i);
    }
    return objectGroups.get(i).getChildAt(0);
}
 
源代码22 项目: weblaf   文件: WebTreeModel.java
/**
 * 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 );
    }
}
 
源代码23 项目: TencentKona-8   文件: Test4631471.java
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);
}
 
源代码24 项目: netbeans   文件: ProfilerTreeTable.java
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);
        }
    };
}
 
源代码25 项目: pumpernickel   文件: LocationTreePaneUI.java
private static TreeNode createRootNode(IOLocation[] rootLocations) {
	DefaultMutableTreeNode root = new DefaultMutableTreeNode();
	for (IOLocation loc : rootLocations) {
		DefaultMutableTreeNode node = new DefaultMutableTreeNode(loc);
		root.add(node);
	}
	return root;
}
 
源代码26 项目: netbeans   文件: HintsPanel.java
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;
    }
 
源代码27 项目: consulo   文件: XDebuggerTreeSpeedSearch.java
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;
}
 
源代码28 项目: java-swing-tips   文件: MainPanel.java
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));
    }
  }
}
 
源代码29 项目: consulo   文件: CommitNode.java
@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()));
}
 
源代码30 项目: fabric-loader   文件: FabricMainWindow.java
private static JPanel createTreePanel(FabricStatusNode rootNode, FabricTreeWarningLevel minimumWarningLevel,
	IconSet iconSet) {
	JPanel panel = new JPanel();
	panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

	TreeNode treeNode = new CustomTreeNode(null, rootNode, minimumWarningLevel);

	DefaultTreeModel model = new DefaultTreeModel(treeNode);
	JTree tree = new JTree(model);
	tree.setRootVisible(false);

	for (int row = 0; row < tree.getRowCount(); row++) {
		if (!tree.isVisible(tree.getPathForRow(row))) {
			continue;
		}

		CustomTreeNode node = ((CustomTreeNode) tree.getPathForRow(row).getLastPathComponent());

		if (node.node.expandByDefault || node.node.getMaximumWarningLevel().isAtLeast(FabricTreeWarningLevel.WARN)) {
			tree.expandRow(row);
		}
	}

	ToolTipManager.sharedInstance().registerComponent(tree);
	tree.setCellRenderer(new CustomTreeCellRenderer(iconSet));

	JScrollPane scrollPane = new JScrollPane(tree);
	panel.add(scrollPane);

	return panel;
}
 
 类所在包
 同包方法