下面列出了怎么用javax.swing.tree.TreeModel的API类实例代码及写法,或者点击链接到github查看源代码。
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());
}
/**
* 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;
}
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;
}
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;
}
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);
}
}
}
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);
}
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();
}
}
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);
}
}
});
}
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();
}
}
/**
* 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());
}
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();
}
}
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);
}
}
});
}
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);
}
}
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());
}
@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 );
}
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)));
}
}
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);
}
}
/**
* 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;
}
}
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;
});
}
/**
* 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)));
}
}
/**
* 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();
}
/**
* 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();
}
});
}
}
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;
}
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;
}
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);
}
private static TreeModel makeModel() {
DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
root.add(new DefaultMutableTreeNode("Introduction"));
root.add(makePart());
root.add(makePart());
return new DefaultTreeModel(root);
}
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;
}
};
}
/**
* 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();
}
/**
* 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;
}
}
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));
}
}