Java Code Examples for javax.swing.tree.DefaultMutableTreeNode#getPath()

The following examples show how to use javax.swing.tree.DefaultMutableTreeNode#getPath() . 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: AbstractProjectViewPane.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void expand(@Nullable final Object[] path, final boolean requestFocus) {
  if (getTreeBuilder() == null || path == null) return;
  AbstractTreeUi ui = getTreeBuilder().getUi();
  if (ui != null) ui.buildNodeForPath(path);

  DefaultMutableTreeNode node = ui == null ? null : ui.getNodeForPath(path);
  if (node == null) {
    return;
  }
  TreePath treePath = new TreePath(node.getPath());
  myTree.expandPath(treePath);
  if (requestFocus) {
    IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> IdeFocusManager.getGlobalInstance().requestFocus(myTree, true));
  }
  TreeUtil.selectPath(myTree, treePath);
}
 
Example 2
Source File: ProjectTree.java    From TrakEM2 with GNU General Public License v3.0 6 votes vote down vote up
/** Move up (-1) or down (1). */
private void move(final DefaultMutableTreeNode node, final int direction) {
	final ProjectThing pt = (ProjectThing)node.getUserObject();
	if (null == pt) return;
	// Move: within the list of children of the parent ProjectThing:
	if (!pt.move(direction)) return;
	// If moved, reposition within the list of children
	final DefaultMutableTreeNode parent_node = (DefaultMutableTreeNode)node.getParent();
	int index = parent_node.getChildCount() -1;
	((DefaultTreeModel)this.getModel()).removeNodeFromParent(node);
	index = pt.getParent().getChildren().indexOf(pt);
	((DefaultTreeModel)this.getModel()).insertNodeInto(node, parent_node, index);
	// restore selection path
	final TreePath trp = new TreePath(node.getPath());
	this.scrollPathToVisible(trp);
	this.setSelectionPath(trp);
	this.updateUILater();
}
 
Example 3
Source File: ManageInspectionsOperatot.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private TreeNode[] getPath(Object node, String deap, String item, boolean debug) {
    if (node instanceof DefaultMutableTreeNode) {
        DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode) node;
        if (debug) {
            System.out.println(deap + dmtn.toString());
        }
        if (dmtn.toString().equals(item)) {
            if (debug) {
                System.out.println("EQUAL!!! <" + item + ">");
            }
            return dmtn.getPath();
        }
        TreeNode[] curPath;
        for (int i = 0; i < dmtn.getChildCount(); i++) {
            curPath = getPath(dmtn.getChildAt(i), deap + "__", item, debug);
            if (curPath != null) {
                return curPath;
            }
        }
    }
    return null;
}
 
Example 4
Source File: FilterOpUI.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private static void expandAll(JTree tree) {
    DefaultMutableTreeNode actNode = (DefaultMutableTreeNode) tree.getModel().getRoot();
    while (actNode != null) {
        if (!actNode.isLeaf()) {
            final TreePath actPath = new TreePath(actNode.getPath());
            tree.expandRow(tree.getRowForPath(actPath));
        }
        actNode = actNode.getNextNode();
    }
}
 
Example 5
Source File: UMLModelASTReader.java    From RefactoringMiner with MIT License 5 votes vote down vote up
private String getAnonymousBinaryName(DefaultMutableTreeNode node) {
	StringBuilder name = new StringBuilder();
	TreeNode[] path = node.getPath();
	for(int i=0; i<path.length; i++) {
		DefaultMutableTreeNode tmp = (DefaultMutableTreeNode)path[i];
		if(tmp.getUserObject() != null) {
			DefaultMutableTreeNode parent = (DefaultMutableTreeNode)tmp.getParent();
			int index = parent.getIndex(tmp);
			name.append(index+1);
			if(i < path.length-1)
				name.append(".");
		}
	}
	return name.toString();
}
 
Example 6
Source File: TemplateListPanel.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void setSelectedNode(DefaultMutableTreeNode node) {
  TreePath path = new TreePath(node.getPath());
  myTree.expandPath(path.getParentPath());
  int row = myTree.getRowForPath(path);
  myTree.setSelectionRow(row);
  myTree.scrollRowToVisible(row);
}
 
Example 7
Source File: OutputReview.java    From ciscorouter with MIT License 5 votes vote down vote up
/**
 * Deletes the selected node from the tree and removes the corresponding entry from the report.
 * @param evt
 */
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
    selected = (DefaultMutableTreeNode) reportTree.getLastSelectedPathComponent();
    if (selected == null) {
        //Nothing is selected
        return;
    }
    //If it's a host
    if (selected.getPath().length == 2) {
        String hostname = selected.toString();
        int toDelete = this.getIndexOfHost(hostname);
        if (toDelete == -1) {
            return;
        }
        report.getReports().remove(toDelete);
    } else if (selected.getPath().length == 3) { //If it's a rule
        String host = selected.getParent().toString();
        String rule = selected.toString();
        int hostNum = this.getIndexOfHost(host);
        int ruleNum = this.getIndexOfRule(hostNum, rule);
        if (hostNum == -1 || ruleNum == -1) {
            return;
        }
        report.getReports().get(hostNum).getMatchedRules().remove(ruleNum);
    }
    MutableTreeNode parent = (MutableTreeNode) selected.getParent();
    int index = parent.getIndex(selected);
    parent.remove(selected);
    model.nodesWereRemoved(parent, new int[]{index}, new Object[]{selected});
    reportTree.setModel(model);

}
 
Example 8
Source File: InspectorPanel.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private TreePath getTreePath(DiagnosticsNode node) {
  if (node == null) {
    return null;
  }
  final DefaultMutableTreeNode treeNode = valueToTreeNode.get(node.getValueRef());
  if (treeNode == null) {
    return null;
  }
  return new TreePath(treeNode.getPath());
}
 
Example 9
Source File: InspectorTreeUI.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Rectangle getSubtreeBounds(DefaultMutableTreeNode node, Rectangle clipBounds) {
  if (node == null) {
    return null;
  }
  final TreePath path = new TreePath(node.getPath());
  final int depth = path.getPathCount() - 1;
  final Rectangle rootBounds = tree.getPathBounds(path);
  if (rootBounds == null) {
    return null;
  }
  // We use getRowX instead of the value from rootBounds as we want to include
  // the down arrows
  final int minX = getRowX(-1, depth - 1);
  final int minY = rootBounds.y;

  Rectangle bounds;
  final Rectangle descendantBounds = tree.getPathBounds(getLastExpandedDescendant(path));
  if (descendantBounds != null) {
    final int maxY = (int)descendantBounds.getMaxY();
    final int maxX = (int)clipBounds.getMaxX();
    bounds = new Rectangle(minX, minY, maxX - minX, maxY - minY);
  }
  else {
    // This case shouldn't really happen unless we have a bug but using just
    // the root node bounds is a safe fallback.
    bounds = rootBounds;
  }
  return bounds.intersection(clipBounds);
}
 
Example 10
Source File: InspectorPanel.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private TreePath getTreePath(DiagnosticsNode node) {
  if (node == null) {
    return null;
  }
  final DefaultMutableTreeNode treeNode = valueToTreeNode.get(node.getValueRef());
  if (treeNode == null) {
    return null;
  }
  return new TreePath(treeNode.getPath());
}
 
Example 11
Source File: ColopediaPanel.java    From freecol with GNU General Public License v2.0 5 votes vote down vote up
private void select(String id) {
    DefaultMutableTreeNode node = nodeMap.get(id);
    if (node == null) {
        logger.warning("Unable to find node with id '" + id + "'.");
    } else {
        TreePath oldPath = tree.getSelectionPath();
        if (oldPath != null && oldPath.getParentPath() != null) {
            tree.collapsePath(oldPath.getParentPath());
        }
        TreePath newPath = new TreePath(node.getPath());
        tree.scrollPathToVisible(newPath);
        tree.expandPath(newPath);
        showDetails((ColopediaTreeItem) node.getUserObject());
    }
}
 
Example 12
Source File: OccurenceNavigatorSupport.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public OccurenceInfo goNextOccurence() {
  DefaultMutableTreeNode node = findNode(myTree, true);
  if (node == null) return null;
  TreePath treePath = new TreePath(node.getPath());
  TreeUtil.selectPath(myTree, treePath);
  Navigatable editSourceDescriptor = createDescriptorForNode(node);
  if (editSourceDescriptor == null) return null;
  Counters counters = calculatePosition(node);
  return new OccurenceInfo(editSourceDescriptor, counters.myFoundOccurenceNumber, counters.myOccurencesCount);
}
 
Example 13
Source File: PathsCustomizer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@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);
        }
    }
}
 
Example 14
Source File: PathsCustomizer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@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);
        }
    }
}
 
Example 15
Source File: TreeUtil.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * @param tree com.sun.java.swing.JTree
 * @param start com.sun.java.swing.tree.DefaultMutableTreeNode
 */
public static void expandTree(JTree tree, TreeNode start, int level) {
    for (Enumeration children = start.children(); children.hasMoreElements();) {
        DefaultMutableTreeNode dtm = (DefaultMutableTreeNode) children.nextElement();
        //System.out.println(dtm.getUserObject()+" "+dtm.getDepth());
        if (!dtm.isLeaf() && dtm.getLevel() <= level) {
            //
            TreePath tp = new TreePath(dtm.getPath());
            tree.expandPath(tp);
            //
            expandTree(tree, dtm, level);
        }
    }
    return;
}
 
Example 16
Source File: ProjectViewTestUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
protected static boolean isExpanded(DefaultMutableTreeNode nodeForElement, AbstractProjectViewPSIPane pane) {
  TreePath path = new TreePath(nodeForElement.getPath());
  return pane.getTree().isExpanded(path.getParentPath());
}
 
Example 17
Source File: DictionariesTree.java    From weblaf with GNU General Public License v3.0 4 votes vote down vote up
public void selectAndShow ( final DefaultMutableTreeNode node )
{
    final TreePath path = new TreePath ( node.getPath () );
    setSelectionPath ( path );
    scrollPathToVisible ( path );
}
 
Example 18
Source File: MainPanel.java    From java-swing-tips with MIT License 4 votes vote down vote up
private MainPanel() {
  super(new BorderLayout());
  ImageIcon icon = new ImageIcon(getClass().getResource("restore_to_background_color.gif"));

  DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
  DefaultMutableTreeNode s0 = new DefaultMutableTreeNode(new NodeObject("default", icon));
  DefaultMutableTreeNode s1 = new DefaultMutableTreeNode(new NodeObject("setImageObserver", icon));
  root.add(s0);
  root.add(s1);
  JTree tree = new JTree(new DefaultTreeModel(root)) {
    @Override public void updateUI() {
      setCellRenderer(null);
      super.updateUI();
      TreeCellRenderer r = getCellRenderer();
      setCellRenderer((tree, value, selected, expanded, leaf, row, hasFocus) -> {
        JLabel l = (JLabel) r.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
        Object v = Optional.ofNullable(value)
            .filter(DefaultMutableTreeNode.class::isInstance).map(DefaultMutableTreeNode.class::cast)
            .map(DefaultMutableTreeNode::getUserObject).orElse(null);
        if (v instanceof NodeObject) {
          NodeObject uo = (NodeObject) v;
          l.setText(Objects.toString(uo.title, ""));
          l.setIcon(uo.icon);
        } else {
          l.setText(Objects.toString(value, ""));
          l.setIcon(null);
        }
        return l;
      });
    }
  };
  TreePath path = new TreePath(s1.getPath());
  // Wastefulness: icon.setImageObserver((ImageObserver) tree);
  icon.setImageObserver((img, infoflags, x, y, w, h) -> {
    if (!tree.isShowing()) {
      return false;
    }
    Rectangle cellRect = tree.getPathBounds(path);
    if ((infoflags & (FRAMEBITS | ALLBITS)) != 0 && Objects.nonNull(cellRect)) {
      tree.repaint(cellRect);
    }
    return (infoflags & (ALLBITS | ABORT)) == 0;
  });
  tree.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
  add(new JScrollPane(tree));
  setPreferredSize(new Dimension(320, 240));
}
 
Example 19
Source File: LayerTree.java    From TrakEM2 with GNU General Public License v3.0 4 votes vote down vote up
/** Used by the Loader.importStack and the "many new layers" command. */
public void addLayer(LayerSet layer_set, Layer layer) {
	if (null == layer_set || null == layer) return;
	try {
		// find the node that contains the LayerSet
		DefaultMutableTreeNode root_node = (DefaultMutableTreeNode)this.getModel().getRoot();
		LayerThing root_lt = (LayerThing)root_node.getUserObject();
		Thing thing = null;
		if (root_lt.getObject().equals(layer_set)) thing = root_lt;
		else thing = root_lt.findChild(layer_set);
		DefaultMutableTreeNode parent_node = DNDTree.findNode(thing, this);
		if (null == parent_node) { Utils.log("LayerTree: LayerSet not found."); return; }
		LayerThing parent_thing = (LayerThing)parent_node.getUserObject();
		double z = layer.getZ();
		// find the node whose 'z' is larger than z, and add the Layer before that.
		int n = parent_node.getChildCount();
		int i = 0;
		for (; i < n; i++) {
			DefaultMutableTreeNode child_node = (DefaultMutableTreeNode)parent_node.getChildAt(i);
			LayerThing child_thing = (LayerThing)child_node.getUserObject();
			if (!child_thing.getType().equals("layer")) {
				continue;
			}
			double iz = ((Layer)child_thing.getObject()).getZ();
			if (iz < z) {
				continue;
			}
			// else, add the layer here, after the 'i' layer which has a larger z
			break;
		}
		TemplateThing tt = parent_thing.getChildTemplate("layer");
		if (null == tt) {
			Utils.log("LayerTree: Null template Thing!");
			return;
		}
		LayerThing new_thing = new LayerThing(tt, layer.getProject(), layer);
		// Add the new_thing to the tree
		if (null != new_thing) {
			parent_thing.addChild(new_thing);
			DefaultMutableTreeNode new_node = new DefaultMutableTreeNode(new_thing);
			//TODO when changing the Z of a layer, the insertion is proper but an empty space is left //Utils.log("LayerTree: inserting at: " + i);
			((DefaultTreeModel)this.getModel()).insertNodeInto(new_node, parent_node, i);
			TreePath treePath = new TreePath(new_node.getPath());
			this.scrollPathToVisible(treePath);
			this.setSelectionPath(treePath);
		}
	} catch (Exception e) { IJError.print(e); }
}
 
Example 20
Source File: ObjectSelector.java    From jaamsim with Apache License 2.0 4 votes vote down vote up
@Override
public void setEntity(Entity ent) {

	if (ent == currentEntity)
		return;
	currentEntity = ent;

	if (tree == null)
		return;

	JaamSimModel simModel = GUIFrame.getJaamSimModel();
	if (simModel == null || simModel.getSimulation() == null)
		return;

	long curSequence = simModel.getEntitySequence();
	if (entSequence != curSequence) {
		entSequence = curSequence;
		updateTree(simModel);
	}

	if (currentEntity == null) {
		tree.setSelectionPath(null);
		tree.setEditable(false);
		return;
	}

	tree.setEditable(true);

	DefaultMutableTreeNode root = (DefaultMutableTreeNode)tree.getModel().getRoot();
	Enumeration<?> e = root.depthFirstEnumeration();
	while (e.hasMoreElements()) {
		DefaultMutableTreeNode aNode = (DefaultMutableTreeNode)e.nextElement();
		if (aNode.getUserObject() == currentEntity) {
			TreePath path = new TreePath(aNode.getPath());
			tree.scrollPathToVisible(path);
			tree.setSelectionPath(path);
			return;
		}
	}

	// Entity not found in the tree
	tree.setSelectionPath(null);
	tree.setEditable(false);
}