下面列出了怎么用javax.swing.tree.MutableTreeNode的API类实例代码及写法,或者点击链接到github查看源代码。
/**
*
* @Title : removeCurrentNode
* @Description: Remove the currently selected node.
* @Param :
* @Return : void
* @Throws :
*/
public void removeCurrentNode()
{
TreePath currentSelection = tree.getSelectionPath();
if (null == currentSelection)
{
return;
}
CheckBoxTreeNode currentNode = (CheckBoxTreeNode) (currentSelection.getLastPathComponent());
MutableTreeNode parent = (MutableTreeNode) (currentNode.getParent());
if (null != parent)
{
treeModel.removeNodeFromParent(currentNode);
return;
}
// Either there was no selection, or the root was selected.
toolkit.beep();
}
/**
* Implementation of javax.swing.tree.DefaultTreeModel#removeNodeFromParent(javax.swing.tree.MutableTreeNode) for multiple nodes.
* Fires a single event, or does nothing when nodes is empty.
*
* @param treeModel to fire the treeNodesRemoved event on
* @param parent the parent
* @param nodes must all be children of parent
*/
private static void removeNodesFromParent(@Nonnull DefaultTreeModel treeModel, @Nonnull GroupNode parent, @Nonnull List<? extends MutableTreeNode> nodes) {
int count = nodes.size();
if (count == 0) {
return;
}
ObjectIntHashMap<MutableTreeNode> ordering = new ObjectIntHashMap<>(count);
for (MutableTreeNode node : nodes) {
ordering.put(node, parent.getIndex(node));
}
Collections.sort(nodes, Comparator.comparingInt(ordering::get)); // need ascending order
int[] indices = ordering.getValues();
Arrays.sort(indices);
for (int i = count - 1; i >= 0; i--) {
parent.remove(indices[i]);
}
treeModel.nodesWereRemoved(parent, indices, nodes.toArray());
}
private MutableTreeNode wrap(final Tree tree) {
if (tree == null) {
return null;
}
DefaultMutableTreeNode root = new DefaultMutableTreeNode(tree) {
@Override
public String toString() {
return treeTextProvider.getText((Tree) getUserObject());
}
};
for (int i = 0; i < tree.getChildCount(); i++) {
root.add(wrap(tree.getChild(i)));
}
return root;
}
public static void sort(DefaultMutableTreeNode parent) {
int n = parent.getChildCount();
for (int i = 0; i < n - 1; i++) {
int min = i;
for (int j = i + 1; j < n; j++) {
if (tnc.compare((DefaultMutableTreeNode) parent.getChildAt(min), (DefaultMutableTreeNode) parent.getChildAt(j)) > 0) {
min = j;
}
}
if (i != min) {
MutableTreeNode a = (MutableTreeNode) parent.getChildAt(i);
MutableTreeNode b = (MutableTreeNode) parent.getChildAt(min);
parent.insert(b, i);
parent.insert(a, min);
updateTree = true;
}
}
}
private boolean checkForDuplicateThreadItem(Map directChildMap, DefaultMutableTreeNode node1) {
ThreadInfo mi1 = (ThreadInfo) node1.getUserObject();
String name1 = mi1.getName();
for (Iterator iter2 = directChildMap.entrySet().iterator(); iter2.hasNext();) {
DefaultMutableTreeNode node2 = (DefaultMutableTreeNode) ((Map.Entry) iter2.next()).getValue();
if (node1 == node2) {
continue;
}
ThreadInfo mi2 = (ThreadInfo) node2.getUserObject();
if (name1.equals(mi2.getName()) && node2.getChildCount() > 0) {
node1.add((MutableTreeNode) node2.getFirstChild());
iter2.remove();
return true;
}
}
return false;
}
private void rangeAxisConfigRemoved(int index, RangeAxisConfig rangeAxis) {
removeNodeFromParent((MutableTreeNode) root.getChildAt(index + NUMBER_OF_PERMANENT_DIMENSIONS));
reload();
plotConfigTree.expandAll();
// Acquire new selection element
int childCount = root.getChildCount();
Object newSelection = null;
if (childCount > NUMBER_OF_PERMANENT_DIMENSIONS) {
newSelection = root.getChildAt(childCount - 1);
} else {
newSelection = root;
}
// change selection path
TreePath path = new TreePath(getPathToRoot((TreeNode) newSelection));
makeVisibleAndSelect(path);
}
/**
* Removes {@code child} from its present parent (if it has a parent), sets the child's parent to this node,
* and then adds the child to this node's child {@link List} at index {@code childIndex}.
* {@code child} must not be {@code null} and must not be an ancestor of this node.
*
* @param child child node to insert under this node
* @param index index in this node's child {@link List} where this node is to be inserted
* @throws IllegalStateException if this node does not allow children
* @throws IllegalArgumentException if {@code child} is null or is an ancestor of this node
* @throws ArrayIndexOutOfBoundsException if {@code childIndex} is out of bounds
* @see #isNodeDescendant(WebTreeNode)
*/
@Override
public void insert ( @NotNull final MutableTreeNode child, final int index )
{
if ( !allowsChildren )
{
throw new IllegalStateException ( "Node does not allow children" );
}
if ( isNodeAncestor ( ( N ) child ) )
{
throw new IllegalArgumentException ( "New child is an ancestor" );
}
final N oldParent = ( N ) child.getParent ();
if ( oldParent != null )
{
oldParent.remove ( child );
}
child.setParent ( this );
if ( children == null )
{
children = new ArrayList<N> ();
}
children.add ( index, ( N ) child );
}
public void removeNodeFromParent(MutableTreeNode node) {
if (!filterIsActive) {
super.removeNodeFromParent(node);
} else {
MutableTreeNode parent = (MutableTreeNode) node.getParent();
if (parent == null)
throw new IllegalArgumentException("node does not have a parent.");
int[] childIndex = new int[1];
Object[] removedArray = new Object[1];
childIndex[0] = ((StructureTreeNode)parent).getIndex(node, filterIsActive);
if ((childIndex[0] != -1) && ((StructureTreeNode)node).isVisible()) {
node.removeFromParent();
removedArray[0] = node;
nodesWereRemoved(parent, childIndex, removedArray);
}
}
}
@Override
public void insert(MutableTreeNode child, int index) {
super.insert(child, index);
Collections.sort(this.children, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof TagNode) {
return -1;
}
if (o2 instanceof TagNode) {
return 1;
}
return o1.toString().compareToIgnoreCase(o2.toString());
}
});
}
/**
* This method selects the first entry in a jTree that start with the text
* that is entered in the filter-textfield.
*
* @param tree the jTree where the item should be selected
* @param textfield the related filtertextfield that contains the user-input
*/
public static void selectByTyping(javax.swing.JTree tree, javax.swing.JTextField textfield) {
DefaultTreeModel dtm = (DefaultTreeModel) tree.getModel();
MutableTreeNode root = (MutableTreeNode) dtm.getRoot();
String text = textfield.getText().toLowerCase();
if (root != null && !text.isEmpty()) {
for (int cnt = 0; cnt < dtm.getChildCount(root); cnt++) {
MutableTreeNode child = (MutableTreeNode) dtm.getChild(root, cnt);
String childtext = child.toString().toLowerCase();
if (childtext.startsWith(text)) {
TreePath tp = new TreePath(root);
tp = tp.pathByAddingChild(child);
tree.setSelectionPath(tp);
tree.scrollPathToVisible(tp);
return;
}
}
}
}
private static void sort2(DefaultMutableTreeNode parent) {
int n = parent.getChildCount();
for (int i = 0; i < n - 1; i++) {
int min = i;
for (int j = i + 1; j < n; j++) {
if (tnc.compare((DefaultMutableTreeNode) parent.getChildAt(min),
(DefaultMutableTreeNode) parent.getChildAt(j)) > 0) {
min = j;
}
}
if (i != min) {
SWAP_COUNTER.getAndIncrement();
MutableTreeNode a = (MutableTreeNode) parent.getChildAt(i);
MutableTreeNode b = (MutableTreeNode) parent.getChildAt(min);
parent.insert(b, i);
parent.insert(a, min);
// MutableTreeNode node = (MutableTreeNode) parent.getChildAt(min);
// parent.insert(node, i);
// COMPARE_COUNTER++;
}
}
}
int removeUsagesBulk(@Nonnull Set<UsageNode> usages, @Nonnull DefaultTreeModel treeModel) {
ApplicationManager.getApplication().assertIsDispatchThread();
int removed = 0;
synchronized (this) {
List<MutableTreeNode> removedNodes = new SmartList<>();
for (UsageNode usage : usages) {
if (myChildren.remove(usage)) {
removedNodes.add(usage);
removed++;
}
}
if (removed == 0) {
for (GroupNode groupNode : getSubGroups()) {
int delta = groupNode.removeUsagesBulk(usages, treeModel);
if (delta > 0) {
if (groupNode.getRecursiveUsageCount() == 0) {
myChildren.remove(groupNode);
removedNodes.add(groupNode);
}
removed += delta;
if (removed == usages.size()) break;
}
}
}
if (!myChildren.isEmpty()) {
removeNodesFromParent(treeModel, this, removedNodes);
}
}
if (removed > 0) {
myRecursiveUsageCount -= removed;
if (myRecursiveUsageCount != 0) {
treeModel.nodeChanged(this);
}
}
return removed;
}
private void removeNode(TreeNode selNode) {
if (selNode == null) {
return;
}
MutableTreeNode parent = (MutableTreeNode) (selNode.getParent());
if (parent == null) {
return;
}
if (selNode.getChildCount() == 0) {
this.model.removeNodeFromParent((MutableTreeNode) selNode);
}
}
/** Remove the currently selected node. */
public void removeCurrentNode() {
TreePath currentSelection = tree.getSelectionPath();
if (currentSelection != null) {
DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode) (currentSelection.getLastPathComponent());
MutableTreeNode parent = (MutableTreeNode) (currentNode.getParent());
if (parent != null) {
treeModel.removeNodeFromParent(currentNode);
return;
}
}
// Either there was no selection, or the root was selected.
toolkit.beep();
}
@Override
public void intervalAdded(ListDataEvent e) {
for (int i = e.getIndex1(); i >= e.getIndex0(); i--) {
Object obj = listModel.getElementAt(i);
if (obj instanceof ClassPathSupport.Item) {
DefaultMutableTreeNode node = toTreeNode(obj);
treeModel.insertNodeInto(node, (MutableTreeNode)treeModel.getRoot(), e.getIndex0());
TreePath path = new TreePath(node.getPath());
tree.setSelectionPath(path);
tree.makeVisible(path);
}
}
}
@Override
public void keyRemoved(MapEvent<String, Integer> e)
{
int index = types.indexOf(e.getKey());
types.remove(index);
removeNodeFromParent((MutableTreeNode) getChildAt(index));
}
@Override
public void elementModified(ListEvent<AbilityFacade> e)
{
//Logging.errorPrint("Modifying " + category + " - " + e.getElement());
MutableTreeNode oldNode = (MutableTreeNode) getChildAt(e.getIndex());
DefaultTreeTableNode node = buildAbilityNode(e.getElement());
node.setUserObject(e.getElement());
insertNodeInto(node, this, e.getIndex());
removeNodeFromParent(oldNode);
}
@Override
public void insertNodeInto ( @NotNull final MutableTreeNode child, @NotNull final MutableTreeNode parent, final int index )
{
// Inserting node
parent.insert ( child, index );
// Firing node addition
nodesWereInserted ( parent, new int[]{ index } );
}
protected MutableTreeNode getRootNode() {
CheckNode root = new CheckNode.CGSClassNode(className);
for (Property property : properties) {
root.add(new CheckNode.CGSPropertyNode(property));
}
return root;
}
public ModelTreeRTStats(MutableTreeNode root) {
// We call constructor of DefaultTreeModel
super(root);
// Take instance of this ModelTree
instance = this;
// We create the ArrayList
nodesSectionsList = new ArrayList();
initColorMap();
// We generate the tree
generateTree();
}
private DefaultMutableTreeNode makeNode(Object userObject,
MutableTreeNode parent) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(userObject);
if (parent != null) {
treeModel.insertNodeInto(node, parent, parent.getChildCount());
}
return node;
}
/**
* 直接通过model来添加新节点,则无需通过调用JTree的updateUI方法
* model.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());
* 直接通过节点添加新节点,则需要调用tree的updateUI方法
*/
private void addNode(DefaultMutableTreeNode pNode, MutableTreeNode newNode){
pNode.add(newNode);
//--------下面代码实现显示新节点(自动展开父节点)-------
DefaultTreeModel model = (DefaultTreeModel) this.templateTree.getModel();
TreeNode[] nodes = model.getPathToRoot(newNode);
TreePath path = new TreePath(nodes);
this.templateTree.scrollPathToVisible(path);
this.templateTree.updateUI();
}
@Override
public void insert(MutableTreeNode child, int index) {
// only modify node if new. ID = 0 indicates loading from existing tree
if (((FamTreeNode) child).famNode.getId() == 1) {
famNode.addNode(((FamTreeNode) child).famNode);
// once read, this is no longer a new node
((FamTreeNode) child).famNode.setId(0);
}
super.insert(child, index);
}
@Override
void addElement(String elementName) {
final MutableTreeNode node;
if (NAME_DELETABLE.equals(elementName)) {
node = closeable;
} else if (NAME_PLAYABLE.equals(elementName)) {
node = playable;
} else if (NAME_RATEABLE.equals(elementName)) {
node = rateable;
} else if (NAME_WARNING.equals(elementName)) {
node = warning;
} else {
throw new IllegalArgumentException("Unrecognized name \""
+ elementName + "\"");
}
Runnable r = new Runnable() {
public void run() {
treeModel.insertNodeInto(node, root, root.getChildCount());
getDecoratedComponent().expandRow(0);
}
};
if (SwingUtilities.isEventDispatchThread()) {
r.run();
} else {
SwingUtilities.invokeLater(r);
}
}
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);
}
}
private MutableTreeNode createIndexesNode(DataSourceMetadata dataSourceMetadata, DataSourceApi dataSourceApi) {
List<Map<String, String>> indexesMetadata =
dataSourceMetadata.getMetadata(Neo4jBoltCypherDataSourceMetadata.INDEXES);
PatchedDefaultMutableTreeNode indexTreeNode = new PatchedDefaultMutableTreeNode(
new MetadataTreeNodeModel(INDEXES,
dataSourceApi,
String.format(INDEXES_TITLE, indexesMetadata.size()),
GraphIcons.Nodes.INDEX));
indexesMetadata
.forEach(row -> indexTreeNode.add(of(new MetadataTreeNodeModel(INDEX, dataSourceApi,
row.get("description").substring(6) + " " + row.get("state")))));
return indexTreeNode;
}
private MutableTreeNode createConstraintsNode(DataSourceMetadata dataSourceMetadata, DataSourceApi dataSourceApi) {
List<Map<String, String>> constraintsMetadata =
dataSourceMetadata.getMetadata(Neo4jBoltCypherDataSourceMetadata.CONSTRAINTS);
PatchedDefaultMutableTreeNode indexTreeNode = new PatchedDefaultMutableTreeNode(
new MetadataTreeNodeModel(CONSTRAINTS, dataSourceApi,
String.format(CONSTRAINTS_TITLE, constraintsMetadata.size()), GraphIcons.Nodes.CONSTRAINT));
constraintsMetadata
.forEach(row ->
indexTreeNode.add(of(new MetadataTreeNodeModel(CONSTRAINT, dataSourceApi,
row.get("description").substring(11)))));
return indexTreeNode;
}
private ListTreeTableModelOnColumns createModel(GraphQueryPlan plan, boolean isProfilePlan) {
MutableTreeNode rootNode = new DefaultMutableTreeNode(plan);
addChildrenPlansToModel(plan, rootNode);
return new ListTreeTableModelOnColumns(rootNode,
isProfilePlan ? getProfileQueryPlanColumns() : getQueryPlanColumns());
}
private void addChildrenPlansToModel(GraphQueryPlan plan, MutableTreeNode node) {
plan.children()
.forEach(p -> {
MutableTreeNode childNode = new DefaultMutableTreeNode(p);
node.insert(childNode, 0);
childNode.setParent(node);
addChildrenPlansToModel(p, childNode);
});
}
/**
* Inserts new child node into parent node at the specified index.
*
* @param child new child node
* @param parent parent node
* @param index insert index
*/
@Override
public void insertNodeInto ( @NotNull final MutableTreeNode child, @NotNull final MutableTreeNode parent, final int index )
{
// Event Dispatch Thread check
WebLookAndFeel.checkEventDispatchThread ();
// Ensure model is installed
checkInstalled ();
final N parentNode = ( N ) parent;
final N childNode = ( N ) child;
// Ensure node children are loaded
if ( parentNode.isLoaded () )
{
// Inserting new raw children
List<N> cachedChildren = rawNodeChildrenCache.get ( parentNode.getId () );
if ( cachedChildren == null )
{
cachedChildren = new ArrayList<N> ( 1 );
rawNodeChildrenCache.put ( parentNode.getId (), cachedChildren );
}
cachedChildren.add ( index, childNode );
cacheNodeById ( childNode );
// Clearing node cache
// That might be required in case nodes were moved inside of the tree
clearNodeChildrenCache ( childNode, false );
// Inserting node
insertNodeIntoImpl ( childNode, parentNode, index );
// Updating parent node sorting and filtering
filterAndSort ( parentNode, false );
}
}