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

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

源代码1 项目: pdfxtk   文件: ChooserTreeView.java
public ChooserTreeView(TreeModel model, TreePath rootPath) {
  setLayout(new BorderLayout());
  JScrollPane pathSP = new JScrollPane(pathView);
  pathView.addChangeListener(this);
  pathSP.setHorizontalScrollBarPolicy(pathSP.HORIZONTAL_SCROLLBAR_ALWAYS);
  pathSP.setVerticalScrollBarPolicy(pathSP.VERTICAL_SCROLLBAR_NEVER); 
  add(pathSP, BorderLayout.NORTH);
  csp = new JScrollPane(content);
  csp.setHorizontalScrollBarPolicy(csp.HORIZONTAL_SCROLLBAR_AS_NEEDED);
  csp.setVerticalScrollBarPolicy(csp.VERTICAL_SCROLLBAR_NEVER); 
  add(csp, BorderLayout.CENTER);
  if(model != null) setModel(model, rootPath);

  content.setCellRenderer(new CellRenderer());    
  content.addMouseListener(Awt.asyncWrapper(mouseAdapter));
  content.setUI(new MultiColumnListUI());
}
 
源代码2 项目: JglTF   文件: ObjectTrees.java
/**
 * Find the nodes that are <code>DefaultMutableTreeNode</code> with
 * a user object that is a {@link NodeEntry} that has the given value,
 * and return them as a (possibly unmodifiable) list.<br>
 * <br>
 * If the given tree model contains elements that are not
 * <code>DefaultMutableTreeNode</code> instances, or contain
 * user objects that are not {@link NodeEntry} instances,
 * then a warning will be printed, and the respective nodes
 * will be omitted in the returned list.
 * 
 * @param treeModel The tree model
 * @param nodeEntryValue The {@link NodeEntry} value
 * @return The nodes 
 */
static List<DefaultMutableTreeNode> findNodesWithNodeEntryValue(
    TreeModel treeModel, Object nodeEntryValue)
{
    Object root = treeModel.getRoot();
    if (!(root instanceof DefaultMutableTreeNode))
    {
        logger.warning("Unexpected node type: "+root.getClass());
        return Collections.emptyList();
    }
    DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode)root;
    List<DefaultMutableTreeNode> result = 
        new ArrayList<DefaultMutableTreeNode>();
    findNodesWithNodeEntryValue(rootNode, nodeEntryValue, result);
    return result;
}
 
源代码3 项目: sakai   文件: ProjectLogicImpl.java
public TreeModel createTreeModelForShoppingPeriod(String userId)
{
	//Returns a List that represents the tree/node architecture:
	//  List{ List{node, List<children>}, List{node, List<children>}, ...}.

	List<List> l1 = getTreeListForUser(DelegatedAccessConstants.SHOPPING_PERIOD_USER, false, false, getShoppingPeriodAdminNodesForUser(userId));

	//order tree model:
	orderTreeModel(l1);

	TreeModel treeModel = convertToTreeModel(l1, DelegatedAccessConstants.SHOPPING_PERIOD_USER, getEntireToolsList(), false, null, null, false);
	
	if(sakaiProxy.isActiveSiteFlagEnabled()){
		if(treeModel != null && treeModel.getRoot() != null){
			setActiveFlagForSiteNodes((DefaultMutableTreeNode) treeModel.getRoot());
		}
	}
	
	return treeModel;
}
 
源代码4 项目: consulo   文件: TreeExpandCollapse.java
public int expand(JTree tree, TreePath path) {
  if (myLevelsLeft == 0) return myExpansionLimit;
  TreeModel model = tree.getModel();
  Object node = path.getLastPathComponent();
  int levelDecrement = 0;
  if (!tree.isExpanded(path) && !model.isLeaf(node)) {
    tree.expandPath(path);
    levelDecrement = 1;
    myExpansionLimit--;
  }
  for (int i = 0; i < model.getChildCount(node); i++) {
    Object child = model.getChild(node, i);
    if (model.isLeaf(child)) continue;
    ExpandContext childContext = new ExpandContext(myExpansionLimit, myLevelsLeft - levelDecrement);
    myExpansionLimit = childContext.expand(tree, path.pathByAddingChild(child));
    if (myExpansionLimit <= 0) return 0;
  }
  return myExpansionLimit;
}
 
源代码5 项目: netbeans-mmd-plugin   文件: NodeFileOrFolder.java
void fireNotifySubtreeChanged(@Nonnull TreeModel model, @Nonnull @MustNotContainNull final List<TreeModelListener> listeners) {
  if (this.parent != null && this.folderFlag) {
    final Object[] childrenObject = new Object[children.size()];
    final int[] indexes = new int[children.size()];
    for (int i = 0; i < this.children.size(); i++) {
      final NodeFileOrFolder c = this.children.get(i);
      childrenObject[i] = c;
      indexes[i] = i;
      c.fireNotifySubtreeChanged(model, listeners);
    }
    final TreeModelEvent event = new TreeModelEvent(model, this.parent.makeTreePath(), indexes, childrenObject);
    for (final TreeModelListener l : listeners) {
      l.treeStructureChanged(event);
    }
  }
}
 
源代码6 项目: openjdk-jdk9   文件: LastNodeLowerHalfDrop.java
protected static TreeModel getTreeModel() {
    root = new DefaultMutableTreeNode("Root");

    a = new DefaultMutableTreeNode("A");
    root.add(a);
    a1 = new DefaultMutableTreeNode("a1");
    a.add(a1);

    b = new DefaultMutableTreeNode("B");
    root.add(b);
    b1 = new DefaultMutableTreeNode("b1");
    b.add(b1);
    b2 = new DefaultMutableTreeNode("b2");
    b.add(b2);

    c = new DefaultMutableTreeNode("C");
    root.add(c);
    c1 = new DefaultMutableTreeNode("c1");
    c.add(c1);
    return new DefaultTreeModel(root);
}
 
源代码7 项目: visualvm   文件: ProfilerTreeTable.java
public void collapseChildren(int row) {
    if (tree != null) try {
        markExpansionTransaction();
        
        TreePath tpath = tree.getPathForRow(row);
        if (tpath == null || tree.isCollapsed(tpath)) return;
        
        TreeModel tmodel = tree.getModel();
        Object selected = tpath.getLastPathComponent();
        
        int nchildren = tmodel.getChildCount(selected);
        for (int i = 0; i < nchildren; i++)
            tree.collapsePath(tpath.pathByAddingChild(tmodel.getChild(selected, i)));
    
    } finally {
        clearExpansionTransaction();
    }
}
 
源代码8 项目: netbeans   文件: Tab.java
private void scrollNodeToVisible( final Node n ) {
    EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            TreeNode tn = Visualizer.findVisualizer(n);
            if (tn == null) {
                return;
            }
            TreeModel model = tree.getModel();
            if (!(model instanceof DefaultTreeModel)) {
                return;
            }
            TreePath path = new TreePath(((DefaultTreeModel) model).getPathToRoot(tn));
            if( null == path )
                return;
            Rectangle r = tree.getPathBounds(path);
            if (r != null) {
                tree.scrollRectToVisible(r);
            }
        }
    });
}
 
源代码9 项目: netbeans   文件: ProfilerTreeTable.java
public void collapseChildren(int row) {
    if (tree != null) try {
        markExpansionTransaction();
        
        TreePath tpath = tree.getPathForRow(row);
        if (tpath == null || tree.isCollapsed(tpath)) return;
        
        TreeModel tmodel = tree.getModel();
        Object selected = tpath.getLastPathComponent();
        
        int nchildren = tmodel.getChildCount(selected);
        for (int i = 0; i < nchildren; i++)
            tree.collapsePath(tpath.pathByAddingChild(tmodel.getChild(selected, i)));
    
    } finally {
        clearExpansionTransaction();
    }
}
 
源代码10 项目: JglTF   文件: GltfBrowserPanel.java
/**
 * Translates one TreePath to a new TreeModel. This methods assumes 
 * DefaultMutableTreeNodes, and identifies the path based on the
 * user objects.
 * 
 * This method is similar to 
 * {@link de.javagl.common.ui.JTrees#translatePath(TreeModel, TreePath)},
 * but returns a "partial" path if the new tree model only contains a
 * subset of the given path.
 * 
 * @param newTreeModel The new tree model
 * @param oldPath The old tree path
 * @return The new tree path
 */
private static TreePath translatePathPartial(
    TreeModel newTreeModel, TreePath oldPath)
{
    Object newRoot = newTreeModel.getRoot();
    List<Object> newPath = new ArrayList<Object>();
    newPath.add(newRoot);
    Object newPreviousElement = newRoot;
    for (int i=1; i<oldPath.getPathCount(); i++)
    {
        Object oldElement = oldPath.getPathComponent(i);
        DefaultMutableTreeNode oldElementNode = 
            (DefaultMutableTreeNode)oldElement;
        Object oldUserObject = oldElementNode.getUserObject();
        
        Object newElement = getChildWith(newPreviousElement, oldUserObject);
        if (newElement == null)
        {
            break;
        }
        newPath.add(newElement);
        newPreviousElement = newElement;
    }
    return new TreePath(newPath.toArray());
}
 
源代码11 项目: netbeans   文件: ProfilerTreeTable.java
public void expandPlainPath(int row, int maxChildren) {
    if (tree != null) try {
        markExpansionTransaction();
        
        TreePath tpath = tree.getPathForRow(row);
        if (tpath == null) return;
        
        TreeModel tmodel = tree.getModel();            
        int childCount = tmodel.getChildCount(tpath.getLastPathComponent());
    
        while (childCount > 0 && childCount <= maxChildren) {
            tpath = tpath.pathByAddingChild(tmodel.getChild(tpath.getLastPathComponent(), 0));
            childCount = tmodel.getChildCount(tpath.getLastPathComponent());
        }

        tree.putClientProperty(UIUtils.PROP_AUTO_EXPANDING, Boolean.TRUE);
        try { tree.expandPath(tpath); selectPath(tpath, true); }
        finally { tree.putClientProperty(UIUtils.PROP_AUTO_EXPANDING, null); }
        
    } finally {
        clearExpansionTransaction();
    }
}
 
源代码12 项目: netbeans   文件: ProjectTab.java
public void scrollToNode(final Node n) {
        // has to be delayed to be sure that events for Visualizers
        // were processed and TreeNodes are already in hierarchy
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                TreeNode tn = Visualizer.findVisualizer(n);
                if (tn == null) {
                    return;
                }
                TreeModel model = tree.getModel();
                if (!(model instanceof DefaultTreeModel)) {
                    return;
                }
                TreePath path = new TreePath(((DefaultTreeModel) model).getPathToRoot(tn));
                Rectangle r = tree.getPathBounds(path);
                if (r != null) {
                    tree.scrollRectToVisible(r);
                }
            }
        });
}
 
源代码13 项目: consulo   文件: TreeState.java
private void applySelectedTo(@Nonnull JTree tree) {
  List<TreePath> selection = new ArrayList<>();
  for (List<PathElement> path : mySelectedPaths) {
    TreeModel model = tree.getModel();
    TreePath treePath = new TreePath(model.getRoot());
    for (int i = 1; treePath != null && i < path.size(); i++) {
      treePath = findMatchedChild(model, treePath, path.get(i));
    }
    ContainerUtil.addIfNotNull(selection, treePath);
  }
  if (selection.isEmpty()) return;
  tree.setSelectionPaths(selection.toArray(TreeUtil.EMPTY_TREE_PATH));
  if (myScrollToSelection) {
    TreeUtil.showRowCentered(tree, tree.getRowForPath(selection.get(0)), true, true);
  }
}
 
源代码14 项目: stendhal   文件: FileTree.java
public FileTree(final String path) throws FileNotFoundException {
	// Create the JTree itself
	super((TreeModel) null);

	// Use horizontal and vertical lines
	putClientProperty("JTree.lineStyle", "Angled");

	// Create the first node
	final FileTreeNode rootNode = new FileTreeNode(null, path);

	// Populate the root node with its subdirectories
	rootNode.populateDirectories(true);
	setModel(new DefaultTreeModel(rootNode));

	// Listen for Tree Selection Events
	addTreeExpansionListener(new TreeExpansionHandler());
}
 
源代码15 项目: weblaf   文件: WebFileTree.java
@Override
public void setModel ( @Nullable final TreeModel newModel )
{
    // Disable asynchronous loading for the model installation time
    // This made to load initial data without delay using EDT
    // This is some kind of workaround for file chooser to allow it proper file expansion on first load
    final boolean async = isAsyncLoading ();
    setAsyncLoading ( false );
    super.setModel ( newModel );
    setAsyncLoading ( async );
}
 
源代码16 项目: TrakEM2   文件: DNDTree.java
static public void expandAllNodes(final JTree tree, final TreePath path) {
	final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
	final TreeModel tree_model = tree.getModel();
	if (tree_model.isLeaf(node)) return;
	tree.expandPath(path);
	final int n_children = tree_model.getChildCount(node);
	for (int i=0; i<n_children; i++) {
		expandAllNodes(tree, path.pathByAddingChild(tree_model.getChild(node, i)));
	}
}
 
源代码17 项目: SNT   文件: PathWindow.java
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);
	}
}
 
源代码18 项目: jdk8u60   文件: ElementTreePanel.java
/**
 * Updates the tree based on the event type. This will invoke either
 * updateTree with the root element, or handleChange.
 */
protected void updateTree(DocumentEvent event) {
    updatingSelection = true;
    try {
        TreeModel model = getTreeModel();
        Object root = model.getRoot();

        for (int counter = model.getChildCount(root) - 1; counter >= 0;
                counter--) {
            updateTree(event, (Element) model.getChild(root, counter));
        }
    } finally {
        updatingSelection = false;
    }
}
 
源代码19 项目: consulo   文件: FileStructurePopup.java
MyTree(TreeModel treeModel) {
  super(treeModel);
  setRootVisible(false);
  setShowsRootHandles(true);

  HintUpdateSupply.installHintUpdateSupply(this, o -> {
    Object value = StructureViewComponent.unwrapValue(o);
    return value instanceof PsiElement ? (PsiElement)value : null;
  });
}
 
源代码20 项目: nextreports-designer   文件: TreeUtil.java
/**
 * Expand a tree node and all its child nodes recursively.
 *
 * @param tree The tree whose nodes to expand.
 * @param path Path to the node to start at.
 */
public static void expandAll(JTree tree, TreePath path) {
    Object node = path.getLastPathComponent();
    TreeModel model = tree.getModel();
    if (model.isLeaf(node)) {
        return;
    }
    tree.expandPath(path);
    int num = model.getChildCount(node);
    for (int i = 0; i < num; i++) {
        expandAll(tree, path.pathByAddingChild(model.getChild(node, i)));
    }
}
 
源代码21 项目: radiance   文件: BreadcrumbTreeAdapterSelector.java
/**
 * Creates an adapter for the specified tree model.
 *
 * @param treeModel     Tree model.
 * @param treeAdapter   Tree adapter. Can not be <code>null</code>.
 * @param isRootVisible If <code>true</code>, the first selector shows the tree root
 *                      node. If <code>false</code>, the first selector shows the tree
 *                      root child nodes.
 */
public BreadcrumbTreeAdapterSelector(TreeModel treeModel,
        TreeAdapter<T> treeAdapter, boolean isRootVisible) {
    super(null);

    this.model = new BreadcrumbBarModel<>();
    this.callback = new TreeCallback(treeModel, treeAdapter, isRootVisible);
    this.callback.setup();

    this.updateUI();
}
 
源代码22 项目: rapidminer-studio   文件: RepositoryManager.java
/**
 * Add a filter to hide parts of the {@link Repository}
 *
 * @param filter
 * 		a custom filter
 * @since 9.3
 */
public void registerRepositoryFilter(RepositoryFilter filter) {
	if (!RapidMiner.getExecutionMode().isHeadless() && filter != null) {
		repositoryFilters.add(filter);
		filter.notificationCallback(() -> {
			TreeModel treeModel = RapidMinerGUI.getMainFrame().getRepositoryBrowser().getRepositoryTree().getModel();
			if (treeModel instanceof RepositoryTreeModel) {
				((RepositoryTreeModel) treeModel).notifyTreeStructureChanged();
			}
		});
	}
}
 
源代码23 项目: consulo   文件: TreeState.java
private boolean visit(@Nonnull JTree tree) {
  TreeModel model = tree.getModel();
  if (!(model instanceof TreeVisitor.Acceptor)) return false;

  expand(tree, promise -> expand(tree).onProcessed(expanded -> {
    if (isSelectionNeeded(expanded, tree, promise)) {
      select(tree).onProcessed(selected -> promise.setResult(null));
    }
  }));
  return true;
}
 
源代码24 项目: marathonv5   文件: JTreeJavaElement.java
private static int getNodeCount(TreeModel model, Object root) {
    int count = model.getChildCount(root);
    for (int i = 0; i < model.getChildCount(root); i++) {
        Object node = model.getChild(root, i);
        count += getNodeCount(model, node);
    }
    return count;
}
 
源代码25 项目: sakai   文件: ProjectLogicImpl.java
public TreeModel createAccessTreeModelForUser(String userId, boolean addDirectChildren, boolean cascade)
{
	boolean shoppingPeriodTool = DelegatedAccessConstants.SHOPPING_PERIOD_USER.equals(userId);
	//Returns a List that represents the tree/node architecture:
	//  List{ List{node, List<children>}, List{node, List<children>}, ...}.
	accessNodes = new ArrayList<String>();
	shoppingPeriodAdminNodes = new ArrayList<String>();
	accessAdminNodes = new ArrayList<String>();

	List<List> l1 = getTreeListForUser(userId, addDirectChildren, cascade, getAccessNodesForUser(userId));
	
	//Remove the shopping period nodes:
	if(l1 != null){
		HierarchyNode hierarchyRoot = hierarchyService.getRootNode(DelegatedAccessConstants.HIERARCHY_ID);
		String hierarchyRootId = "-1";
		if(hierarchyRoot != null){
			hierarchyRootId = hierarchyRoot.id;
		}
		for (Iterator iterator = l1.iterator(); iterator.hasNext();) {
			List list = (List) iterator.next();
			if(!hierarchyRootId.equals(((HierarchyNodeSerialized) list.get(0)).id)){
				iterator.remove();
			}
		}
	}
	//order tree model:
	orderTreeModel(l1);

	return convertToTreeModel(l1, userId, getEntireToolsList(), addDirectChildren, null, null, shoppingPeriodTool);
}
 
源代码26 项目: java-swing-tips   文件: MainPanel.java
private static TreeModel makeModel() {
  DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
  root.add(new DefaultMutableTreeNode("Introduction"));
  root.add(makePart());
  root.add(makePart());
  return new DefaultTreeModel(root);
}
 
源代码27 项目: ontopia   文件: EmbeddedHierarchicalInstancePage.java
protected IModel<TreeModel> createTreeModel(final TopicModel<Topic> hierarchyTopicModel, final TopicModel<Topic> currentNodeModel) {
  final TreeModel treeModel;
  Topic hierarchyTopic = hierarchyTopicModel.getTopic();
  Topic currentNode = currentNodeModel.getTopic();
  
  // find hierarchy definition query for topic
  String query = (hierarchyTopic == null ? null : getDefinitionQuery(hierarchyTopic));

  if (query != null) {
    Map<String,TopicIF> params = new HashMap<String,TopicIF>(2);
    params.put("hierarchyTopic", hierarchyTopic.getTopicIF());
    params.put("currentNode", currentNode.getTopicIF());
    treeModel = TreeModels.createQueryTreeModel(currentNode.getTopicMap(), query, params);
  } else if (currentNode.isTopicType()) {
    // if no definition query found, then show topic in instance hierarchy
    treeModel = TreeModels.createTopicTypesTreeModel(currentNode.getTopicMap(), isAnnotationEnabled(), isAdministrationEnabled());
  } else {
    treeModel = TreeModels.createInstancesTreeModel(OntopolyUtils.getDefaultTopicType(currentNode), isAdministrationEnabled());
  }
  
  return new AbstractReadOnlyModel<TreeModel>() {
    @Override
    public TreeModel getObject() {
      return treeModel;
    }
  };
}
 
源代码28 项目: osp   文件: LibraryTreePanel.java
/**
 * Sets the font level.
 *
 * @param level the desired font level
 */
protected void setFontLevel(int level) {

Object[] toSize = new Object[] {
		splitPane, editorPanel, editorbar, authorField, contactField, keywordsField,
		authorLabel, contactLabel, keywordsLabel, metadataLabel, metadataDropdown};
FontSizer.setFonts(toSize, level);
EntryField.font = authorField.getFont();

// resize treeNodeRenderer and LibraryResource icons
treeNodeRenderer.resizableOpenIcon.resize(FontSizer.getIntegerFactor());
treeNodeRenderer.resizableClosedIcon.resize(FontSizer.getIntegerFactor());
LibraryResource.trackerIcon.resize(FontSizer.getIntegerFactor());
LibraryResource.ejsIcon.resize(FontSizer.getIntegerFactor());
LibraryResource.imageIcon.resize(FontSizer.getIntegerFactor());
LibraryResource.videoIcon.resize(FontSizer.getIntegerFactor());
LibraryResource.htmlIcon.resize(FontSizer.getIntegerFactor());
LibraryResource.pdfIcon.resize(FontSizer.getIntegerFactor());
LibraryResource.unknownIcon.resize(FontSizer.getIntegerFactor());

// resize LibraryResource stylesheet font sizes
LibraryResource.bodyFont = FontSizer.getResizedFont(LibraryResource.bodyFont, level);
LibraryResource.h1Font = FontSizer.getResizedFont(LibraryResource.h1Font, level);
LibraryResource.h2Font = FontSizer.getResizedFont(LibraryResource.h2Font, level);

// clear htmlPanesByNode to force new HTML code with new stylesheets
htmlPanesByNode.clear();

// refresh the tree structure
TreeModel model = tree.getModel();
if (model instanceof DefaultTreeModel) {
	LibraryTreeNode selectedNode = getSelectedNode();
	DefaultTreeModel treeModel = (DefaultTreeModel)model;
	treeModel.nodeStructureChanged(rootNode);
	setSelectedNode(selectedNode);
}
refreshGUI();

}
 
源代码29 项目: openjdk-jdk9   文件: ElementTreePanel.java
/**
 * Updates the tree based on the event type. This will invoke either
 * updateTree with the root element, or handleChange.
 */
protected void updateTree(DocumentEvent event) {
    updatingSelection = true;
    try {
        TreeModel model = getTreeModel();
        Object root = model.getRoot();

        for (int counter = model.getChildCount(root) - 1; counter >= 0;
                counter--) {
            updateTree(event, (Element) model.getChild(root, counter));
        }
    } finally {
        updatingSelection = false;
    }
}
 
源代码30 项目: RobotBuilder   文件: IconView.java
public IconView(Palette palette) {
    this.palette = palette;

    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

    TreeModel model = palette.getPaletteModel();
    Enumeration children = ((DefaultMutableTreeNode) model.getRoot()).children();
    while (children.hasMoreElements()) {
        DefaultMutableTreeNode child = (DefaultMutableTreeNode) children.nextElement();
        add(new IconSection(child));
    }
}
 
 类所在包
 同包方法