下面列出了怎么用javax.swing.tree.TreePath的API类实例代码及写法,或者点击链接到github查看源代码。
public static ActionUrl getActionUrl(final TreePath treePath, int actionType) {
ActionUrl url = new ActionUrl();
for (int i = 0; i < treePath.getPath().length - 1; i++) {
Object o = ((DefaultMutableTreeNode)treePath.getPath()[i]).getUserObject();
if (o instanceof Group) {
url.getGroupPath().add(((Group)o).getName());
}
}
final DefaultMutableTreeNode component = ((DefaultMutableTreeNode)treePath.getLastPathComponent());
url.setComponent(component.getUserObject());
DefaultMutableTreeNode node = component;
final TreeNode parent = node.getParent();
url.setAbsolutePosition(parent != null ? parent.getIndex(node) : 0);
url.setActionType(actionType);
return url;
}
/**
* Waits path to be collapsed.
*
* @param path a path to wait collapsed.
*/
public void waitCollapsed(final TreePath path) {
if (path != null) {
getOutput().printLine("Wait \"" + path.toString() + "\" path to be collapsed in component \n : "
+ toStringSource());
getOutput().printGolden("Wait \"" + path.toString() + "\" path to be collapsed");
waitState(new ComponentChooser() {
@Override
public boolean checkComponent(Component comp) {
return isCollapsed(path);
}
@Override
public String getDescription() {
return "Has \"" + path.toString() + "\" path collapsed";
}
@Override
public String toString() {
return "JTreeOperator.waitCollapsed.ComponentChooser{description = " + getDescription() + '}';
}
});
} else {
throw (new NoSuchPathException());
}
}
@Override
public void actionPerformed(SymbolTreeActionContext context) {
TreePath[] selectionPaths = context.getSelectedSymbolTreePaths();
if (selectionPaths.length != 1) {
return;
}
Object object = selectionPaths[0].getLastPathComponent();
if (!(object instanceof LibrarySymbolNode) && !(object instanceof ImportsCategoryNode)) {
return;
}
String externalName = null;
if (object instanceof LibrarySymbolNode) {
LibrarySymbolNode libraryNode = (LibrarySymbolNode) object;
externalName = libraryNode.getName();
}
final EditExternalLocationDialog dialog =
new EditExternalLocationDialog(context.getProgram(), externalName);
dialog.setHelpLocation(new HelpLocation("SymbolTreePlugin", "CreateExternalLocation"));
plugin.getTool().showDialog(dialog);
}
private TreePath findDescendant(TreePath path, String name) {
ProgramNode node = (ProgramNode) path.getLastPathComponent();
if (node.getName().equals(name)) {
return node.getTreePath();
}
if (node.getAllowsChildren() && !node.wasVisited()) {
tree.visitNode(node);
}
for (int i = 0; i < node.getChildCount(); i++) {
ProgramNode child = (ProgramNode) node.getChildAt(i);
TreePath p = findDescendant(child.getTreePath(), name);
if (p != null) {
return p;
}
}
return null;
}
/**
*
* @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();
}
public TreePath getInstancePath(Instance instance) {
TreePath instancePath = null;
if (currentlyHasChildren()) {
HeapWalkerNode[] children = getChildren();
for (int i = 0; i < children.length; i++) {
if (children[i] instanceof InstancesListNode) {
instancePath = ((InstancesListNode) children[i]).getInstancePath(instance);
if (instancePath != null) {
break;
}
}
}
}
return instancePath;
}
/**
* Expands all {@link TreeNode}s loaded within {@link JTree} in a single call.
*
* @param tree {@link JTree} to expand {@link TreeNode}s for
* @param node {@link TreeNode} under which all other {@link TreeNode}s should be expanded
*/
public static void expandLoaded ( @NotNull final JTree tree, @NotNull final TreeNode node )
{
// Only expand parent for non-root nodes
if ( node.getParent () != null )
{
// Make sure this node's parent is expanded
// We do not need to expand the node itself, we only need to make sure it is visible in the tree
final TreePath path = getTreePath ( node.getParent () );
if ( !tree.isExpanded ( path ) )
{
tree.expandPath ( path );
}
}
// Expanding all child nodes
// We are asking node instead of tree model to avoid any additional data loading to occur
for ( int index = 0; index < node.getChildCount (); index++ )
{
expandLoaded ( tree, node.getChildAt ( index ) );
}
}
private void makeSelectionFromPaths(TreePath[] paths, boolean selectSource) {
AddressSet set = new AddressSet();
for (TreePath path : paths) {
CallNode callNode = (CallNode) path.getLastPathComponent();
Address address = null;
if (selectSource) {
address = callNode.getSourceAddress();
}
else {
address = callNode.getLocation().getAddress();
}
set.addRange(address, address);
}
ProgramSelection selection = new ProgramSelection(set);
tool.firePluginEvent(
new ProgramSelectionPluginEvent(plugin.getName(), selection, currentProgram));
}
/**
* Creates a repository location out of the user choice. Either uses the selected entry, or creates a location
* relative to the selected plus the location field text, or if nothing is selected creates an absolute path based
* on the location field text.
*
* @return the location, never {@code null}
* @throws MalformedRepositoryLocationException if the entered location does not represent a proper repository
* location
* @since 9.7
*/
public RepositoryLocation getAsRepositoryLocation() throws MalformedRepositoryLocationException {
final TreePath path = tree.getSelectionPath();
if (path == null || !(path.getLastPathComponent() instanceof Entry)) {
// nothing selected in tree, only some value entered in name field. Take it, but who knows what it is
return new RepositoryLocationBuilder().withLocationType(RepositoryLocationType.UNKNOWN).buildFromAbsoluteLocation(getLocationNameFieldText());
}
Entry selectedEntry = (Entry) path.getLastPathComponent();
RepositoryLocation selectedLocation = selectedEntry.getLocation();
if (selectedEntry instanceof Folder) {
// folder selected, but the name field may contain more
if (getLocationNameFieldText().isEmpty()) {
// no custom name entered, it's a folder
selectedLocation = new RepositoryLocationBuilder().withLocationType(RepositoryLocationType.FOLDER).buildFromAbsoluteLocation(selectedLocation.getAbsoluteLocation());
} else {
// custom name entered, who knows what it is, may have more than a single hit there
selectedLocation = new RepositoryLocationBuilder().withLocationType(RepositoryLocationType.UNKNOWN).
buildFromParentLocation(selectedLocation, getLocationNameFieldText());
}
} else {
// data entry selected, take it
selectedLocation = new RepositoryLocationBuilder().withExpectedDataEntryType(((DataEntry) selectedEntry).getClass()).buildFromAbsoluteLocation(selectedLocation.getAbsoluteLocation());
}
return selectedLocation;
}
@Override
public final void dataRemoved(DataSet data) {
DefaultMutableTreeNode root = (DefaultMutableTreeNode) ((DefaultTreeModel) tree.getModel()).getRoot();
for (int i = 0; i < root.getChildCount(); i++) {
DataSet toSearch = (DataSet) ((DefaultMutableTreeNode) root.getChildAt(i)).getUserObject();
if (toSearch.equals(data)) {
Object removed = root.getChildAt(i);
root.remove(i);
((javax.swing.tree.DefaultTreeModel) tree.getModel()).nodesWereRemoved(root, new int[] { i },
new Object[] { removed });
// to remove a node requires it to be selected, so move the selection to the root
tree.setSelectionPath(new TreePath(root));
break;
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
TreePath[] paths = table.getTreeSelectionModel()
.getSelectionPaths();
List<Row> list = SelectableTableView
.showRowSelectDialog(component, framework, engine,
accessRules, qualifier, SelectType.RADIO);
if ((list != null) && (list.size() == 1)) {
Element element = list.get(0).getElement();
ArrayList<Element> elements = new ArrayList<Element>(
paths.length);
for (TreePath path : paths) {
Row row = ((TreeTableNode) path.getLastPathComponent())
.getRow();
if (row != null)
if (!element.equals(row.getElement())) {
elements.add(row.getElement());
}
}
component.getRowSet().startUserTransaction();
engine.replaceElements(
elements.toArray(new Element[elements.size()]), element);
component.getRowSet().commitUserTransaction();
}
}
@Override
protected void paintExpandControl(Graphics g,
Rectangle clipBounds,
Insets insets,
Rectangle bounds,
TreePath path,
int row,
boolean isExpanded,
boolean hasBeenExpanded,
boolean isLeaf) {
boolean isPathSelected = tree.getSelectionModel().isPathSelected(path);
if (!isLeaf(row)) {
setExpandedIcon(DarculaUIUtil.getTreeNodeIcon(true, isPathSelected, tree.hasFocus()));
setCollapsedIcon(DarculaUIUtil.getTreeNodeIcon(false, isPathSelected, tree.hasFocus()));
}
super.paintExpandControl(g, clipBounds, insets, bounds, path, row, isExpanded, hasBeenExpanded, isLeaf);
}
@Override
protected Transferable createTransferable(JComponent component) {
if (component instanceof JTree) {
JTree tree = (JTree)component;
TreePath[] selection = tree.getSelectionPaths();
if (selection != null && selection.length > 1) {
return new TransferableList<TreePath>(selection) {
@Override
protected String toString(TreePath path) {
return String.valueOf(path.getLastPathComponent());
}
};
}
}
return null;
}
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
Component result = myRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
Object treeNode = null;
final int modelRow = table.convertRowIndexToModel(row);
if (myCurrentView == myTreeView) {
TreePath path = myTreeView.getTree().getPathForRow(modelRow);
if (path != null) {
treeNode = path.getLastPathComponent();
}
}
else if (myCurrentView == myFlatView) {
treeNode = myFlatView.getItems().get(modelRow);
}
myCellWrapper.wrap(result, table, value, isSelected, hasFocus, row, column, treeNode);
return result;
}
private void popupInvoked(final Component comp, final int x, final int y) {
Object userObject = null;
final TreePath path = tree.getSelectionPath();
if(path != null) {
final DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
if(node != null) {
userObject = node.getUserObject();
}
}
ActionManager actionManager = ActionManager.getInstance();
DefaultActionGroup group = new DefaultActionGroup();
if(
userObject instanceof SlingServerNodeDescriptor ||
userObject instanceof SlingServerModuleNodeDescriptor
) {
group.add(actionManager.getAction("AEM.Connection.Popup"));
} else {
group.add(actionManager.getAction("AEM.Root.Popup"));
}
final ActionPopupMenu popupMenu = ActionManager.getInstance().createActionPopupMenu(ActionPlaces.ANT_EXPLORER_POPUP, group);
popupMenu.getComponent().show(comp, x, y);
}
/**
* Invokes the <code>getRowForPath</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int getRowForPath(JTree a, TreePath b) {
int returnValue =
((TreeUI) (uis.elementAt(0))).getRowForPath(a,b);
for (int i = 1; i < uis.size(); i++) {
((TreeUI) (uis.elementAt(i))).getRowForPath(a,b);
}
return returnValue;
}
public void addDataSource(String name) {
DBBrowserNode node = searchNode(DBNodeExpander.CONNECTIONS);
// possibly node was not expanded, give it a chance to load children
if (node.getChildCount() == 0) {
startExpandingTree(node, false, null);
}
DBBrowserNode dsNode = new DBBrowserNode(new DBObject(name, null, DBObject.DATABASE));
dsNode.setAllowsChildren(true);
DBBrowserNode foundNode = searchNode(name, DBObject.DATABASE);
if (foundNode == null) {
TreePath path = instance.getSelectionPath();
Enumeration<TreePath> expandedPath = instance.getExpandedDescendants(path);
int size = node.getChildCount();
int insertedIndex = size;
for (int i = 0; i < size; i++) {
DBBrowserNode child = (DBBrowserNode) node.getChildAt(i);
if (Collator.getInstance().compare(name, child.getDBObject().getName()) < 0) {
insertedIndex = i;
break;
}
}
node.insert(dsNode, insertedIndex);
model.nodeStructureChanged(node);
// keep expanded path
if (expandedPath != null) {
while (expandedPath.hasMoreElements()) {
instance.expandPath(expandedPath.nextElement());
}
}
}
}
@Override
public void mouseClicked(MouseEvent e) {
Point p = e.getPoint();
TreePath path = cfgTree.getPathForLocation(e.getPoint().x, e.getPoint().y);
if ( path != null ) {
Rectangle r = cfgTree.getPathBounds(path);
if (r != null) {
if ( r.contains(p)) {
toggle( path );
}
}
}
}
public void mouseClicked(MouseEvent e) {
Point p = e.getPoint();
TreePath path = cfgTree.getPathForLocation(e.getPoint().x, e.getPoint().y);
if ( path != null ) {
Rectangle r = cfgTree.getPathBounds(path);
if (r != null) {
if ( r.contains(p)) {
toggle( path );
}
}
}
}
/**
* Represents a change in the selection of a TreeSelectionModel.
* path identifies the path that have been either added or
* removed from the selection.
*
* @param source source of event
* @param path the path that has changed in the selection
* @param isNew whether or not the path is new to the selection, false
* means path was removed from the selection.
*/
public TreeSelectionEvent(Object source, TreePath path, boolean isNew,
TreePath oldLeadSelectionPath,
TreePath newLeadSelectionPath)
{
super(source);
paths = new TreePath[1];
paths[0] = path;
areNew = new boolean[1];
areNew[0] = isNew;
this.oldLeadSelectionPath = oldLeadSelectionPath;
this.newLeadSelectionPath = newLeadSelectionPath;
}
@Override
public TreePath stringToPath(String value) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)treeModel.getRoot();
if (designSupport.isSimpleExpression(value)) {
value = designSupport.unwrapSimpleExpression(value);
} else {
if ("null".equals(value)) { // NOI18N
return new TreePath(new Object[] {node, node.getChildAt(0)});
}
return null;
}
List<DefaultMutableTreeNode> path = new LinkedList<DefaultMutableTreeNode>();
// always include root
path.add(node);
int index;
while ((index = value.indexOf('.')) != -1) {
String item = value.substring(0, index);
node = findNode(node, item);
if (node == null) {
return null;
} else {
path.add(node);
}
value = value.substring(index+1);
}
// add last
node = findNode(node, value);
if (node != null) {
path.add(node);
} else {
return null;
}
return new TreePath(path.toArray());
}
@Override public boolean isCellEditable(EventObject e) {
if (e instanceof MouseEvent && e.getSource() instanceof JTree) {
MouseEvent me = (MouseEvent) e;
JTree tree = (JTree) me.getComponent();
TreePath path = tree.getPathForLocation(me.getX(), me.getY());
if (path != null && path.getLastPathComponent() instanceof TreeNode) {
return ((TreeNode) path.getLastPathComponent()).isLeaf();
}
}
return false;
}
public void expandPath(TreePath path) {
if (tree != null) try {
markExpansionTransaction();
tree.putClientProperty(UIUtils.PROP_AUTO_EXPANDING, Boolean.TRUE);
try { tree.expandPath(path); }
finally { tree.putClientProperty(UIUtils.PROP_AUTO_EXPANDING, null); }
} finally {
clearExpansionTransaction();
}
}
private void syncTreeSelection() {
programaticSelectionChangeInProgress = true;
final TreePath path = selectedNode != null ? new TreePath(selectedNode.getPath()) : null;
myRootsTree.setSelectionPath(path);
programaticSelectionChangeInProgress = false;
myRootsTree.expandPath(path);
animateTo(selectedNode);
}
private void selectNodes(GTreeNode... nodes) {
List<TreePath> paths = new ArrayList<TreePath>(nodes.length);
for (GTreeNode node : nodes) {
paths.add(node.getTreePath());
}
tree.setSelectionPaths(paths);
waitForTree();
}
@Test
public void testSetGroupSelection() {
setTreeView("Main Tree");
expandRoot();
GroupPath[] gps = new GroupPath[1];
gps[0] = new GroupPath(new String[] { root.getName(), "DLLs" });
plugin.setGroupSelection(gps);
TreePath[] paths = getSelectionPaths();
assertNotNull(paths);
assertEquals(1, paths.length);
assertEquals("DLLs", ((ProgramNode) paths[0].getLastPathComponent()).getName());
}
@Override
protected void initTree() {
if (myWasTreeInitialized) return;
myWasTreeInitialized = true;
super.initTree();
new TreeSpeedSearch(myTree, new Convertor<TreePath, String>() {
@Override
public String convert(final TreePath treePath) {
return ((MyNode)treePath.getLastPathComponent()).getDisplayName();
}
}, true);
ToolTipManager.sharedInstance().registerComponent(myTree);
myTree.setCellRenderer(new ProjectStructureElementRenderer(myContext));
}
@Override
public void insertedNode(final CCriteriumTree criteriumTree, final ICriteriumTreeNode parent,
final ICriteriumTreeNode child) {
final JCriteriumTreeNode parentNode =
findParentNode((JCriteriumTreeNode) getRoot(), parent.getCriterium());
final JCriteriumTreeNode newNode =
new JCriteriumTreeNode(criteriumTree, child.getCriterium(), m_criteria);
final List<JCriteriumTreeNode> grandChildren = new ArrayList<JCriteriumTreeNode>();
final Enumeration<?> enumeration = parentNode.children();
// has to be cached, other wise hasMoreElements returns false when child count / 2 is reached
while (enumeration.hasMoreElements()) {
grandChildren.add((JCriteriumTreeNode) enumeration.nextElement());
}
// can't be done within the above while loop
for (final JCriteriumTreeNode grandChild : grandChildren) {
newNode.add(grandChild);
grandChild.setParent(newNode);
}
parentNode.removeAllChildren();
parentNode.add(newNode);
newNode.setParent(parentNode);
nodeStructureChanged(parentNode);
m_jtree.setSelectionPath(new TreePath(newNode.getPath()));
child.getCriterium().addListener(m_internalCriteriumListener);
}
private void expandAll(TreePath path) {
TreeNode node = (TreeNode) path.getLastPathComponent();
if (node.getChildCount() >= 0) {
Enumeration enumeration = node.children();
while (enumeration.hasMoreElements()) {
TreeNode n = (TreeNode) enumeration.nextElement();
TreePath p = path.pathByAddingChild(n);
expandAll(p);
}
}
this.expandPath(path);
}
@Override public void treeWillExpand(TreeExpansionEvent e) throws ExpandVetoException {
TreePath path = e.getPath();
Object o = path.getLastPathComponent();
if (o instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) o;
File file = (File) node.getUserObject();
String name = file.getName();
// System.out.println(name);
if (!name.isEmpty() && name.codePointAt(0) == '.') {
throw new ExpandVetoException(e, "Tree expansion cancelled");
}
}
}