Java Code Examples for javax.swing.tree.TreePath

The following are top voted examples for showing how to use javax.swing.tree.TreePath. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Cognizant-Intelligent-Test-Scripter   File: TreeSearch.java   Source Code and License 6 votes vote down vote up
public static TreeSearch installForOR(JTree tree) {
    return new TreeSearch(tree) {
        @Override
        public void selectAndSrollTo(TreeNode node) {
            if (node instanceof ORObjectInf) {
                TreePath path = ((ORObjectInf) node).getTreePath();
                tree.setSelectionPath(path);
                tree.scrollPathToVisible(path);
            } else {
                super.selectAndSrollTo(node);
            }
        }
    };
}
 
Example 2
Project: CodeGenerate   File: CheckTreeSelectionModel.java   Source Code and License 6 votes vote down vote up
private boolean areSiblingsSelected(TreePath path) {
    TreePath parent = path.getParentPath();
    if (parent == null) {
        return true;
    }
    Object node = path.getLastPathComponent();
    Object parentNode = parent.getLastPathComponent();

    int childCount = model.getChildCount(parentNode);
    for (int i = 0; i < childCount; i++) {
        Object childNode = model.getChild(parentNode, i);
        if (childNode == node) {
            continue;
        }
        if (!isPathSelected(parent.pathByAddingChild(childNode))) {
            return false;
        }
    }
    return true;
}
 
Example 3
Project: incubator-netbeans   File: CheckTreeView.java   Source Code and License 6 votes vote down vote up
private boolean toggle( TreePath treePath ) {
    
    if( treePath == null )
        return false;
    
    Node node = Visualizer.findNode( treePath.getLastPathComponent() );
    if( node == null )
        return false ;

    ElementNode.Description description = node.getLookup().lookup(ElementNode.Description.class);
    if (description != null ) {
        if( description.isSelectable()  ) {
            description.setSelected( !description.isSelected() );
            return true;
        } else {
            boolean newState = !description.isSelected();
            toggleChildren( description.getSubs(), newState );
            // first toggle children, then itself. If children were not expanded,
            // the self-toggle will fire appropriate events and controls will be reevaluated.
            description.setSelected(newState);
        }
    }
    
    return false;
}
 
Example 4
Project: incubator-netbeans   File: ProfilerTreeTable.java   Source Code and License 6 votes vote down vote up
void selectPath(TreePath path, boolean scrollToVisible) {
        internal = true;
        markExpansionTransaction();
        try {
//            tree.expandPath(path); // actually should not be needed, automatically expands the node further down
            tree.setSelectionPath(path);
            // Clear and select again to make sure the underlying tree is ready
            tree.setSelectionPath(null);
            tree.setSelectionPath(path);
        } finally {
            clearExpansionTransaction();
            internal = false;
        }
        
        if (scrollToVisible) {
            Rectangle bounds = tree.getPathBounds(path);
            if (bounds != null) scrollRectToVisible(bounds);
        }
    }
 
Example 5
Project: rapidminer   File: PlotConfigurationTree.java   Source Code and License 6 votes vote down vote up
/**
 * Opens all paths in the given node and all nodes below that.
 *
 * @param path
 *            the tree path to the node to expand
 * @param treeModel
 *            the tree model
 * @see JTree#expandPath(TreePath)
 */
protected void expandAllPaths(TreePath path, TreeModel treeModel) {
	expandPath(path);
	final Object node = path.getLastPathComponent();
	final int n = treeModel.getChildCount(node);
	for (int index = 0; index < n; index++) {
		final Object child = treeModel.getChild(node, index);
		expandAllPaths(path.pathByAddingChild(child));
	}
}
 
Example 6
Project: ISO8583   File: SortTreeHelper.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public static void sortTree(PnlGuiConfig pnlGuiConfig, DefaultMutableTreeNode root, JTree treeTypes) {
	if (root != null) {
		Enumeration e = root.depthFirstEnumeration();
		while (e.hasMoreElements()) {
			DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement();
			if (!node.isLeaf()) {
				sort(node);   //selection sort
			}
		}
		
		//Atualizando a arvore
		if (updateTree) {
			TreePath treePath = treeTypes.getSelectionPath();
			DefaultTreeModel model = (DefaultTreeModel) treeTypes.getModel();
			model.reload();
			treeTypes.setSelectionPath(treePath);
			updateTree = false;
		}

		pnlGuiConfig.getPnlFieldCondition().ckDynamicClick();
	}
}
 
Example 7
Project: https-github.com-apache-zookeeper   File: ZooInspectorTreeViewer.java   Source Code and License 6 votes vote down vote up
/**
 * @return {@link List} of the currently selected nodes
 */
public List<String> getSelectedNodes() {
    TreePath[] paths = tree.getSelectionPaths();
    List<String> selectedNodes = new ArrayList<String>();
    if (paths != null) {
        for (TreePath path : paths) {
            StringBuilder sb = new StringBuilder();
            Object[] pathArray = path.getPath();
            for (Object o : pathArray) {
                String nodeName = o.toString();
                if (nodeName.length() > 0) {
                    sb.append("/");
                    sb.append(o.toString());
                }
            }
            selectedNodes.add(sb.toString());
        }
    }
    return selectedNodes;
}
 
Example 8
Project: JavaGraph   File: CheckboxTree.java   Source Code and License 6 votes vote down vote up
/**
 * Constructs a tree, with cell renderer and editor set by
 * {@link #createRenderer()} and {@link #createEditor()}.
 */
public CheckboxTree() {
    setCellRenderer(createRenderer());
    setCellEditor(createEditor());
    setEditable(true);
    setRootVisible(false);
    setShowsRootHandles(true);
    // make sure the checkbox never selects the label
    // note that the BasicTreeUI may not be what is used in the current LAF,
    // but I don't know any other way to modify the selection behaviour
    BasicTreeUI ui = new BasicTreeUI() {
        @Override
        protected void selectPathForEvent(TreePath path, MouseEvent event) {
            if (!isOverCheckBox(path, event.getPoint().x)) {
                super.selectPathForEvent(path, event);
            }
        }
    };
    setUI(ui);
    // initialise the tree model
    this.topNode = new DefaultMutableTreeNode();
    this.treeModel = new DefaultTreeModel(this.topNode);
    setModel(this.treeModel);
    // set selection mode
    getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
}
 
Example 9
Project: incubator-netbeans   File: TreeView.java   Source Code and License 6 votes vote down vote up
/** Synchronize the explored context from the manager of this Explorer.
*/
final void synchronizeExploredContext() {
    final Node n = manager.getExploredContext();
    if (n == null) {
        return;
    }

    // run safely to be sure all preceding events are processed (especially VisualizerEvent.Added)
    // otherwise VisualizerNodes may not be in hierarchy yet (see #140629)
    VisualizerNode.runSafe(new Runnable() {
        @Override
        public void run() {
            final TreePath tp = getTreePath(n);
            LOG.log(Level.FINE, "synchronizeExploredContext {0} path {1}", new Object[] { n, tp });
            showPath(tp);
        }
    });
}
 
Example 10
Project: Tarski   File: OurTree.java   Source Code and License 6 votes vote down vote up
/** Construct a Tree object with the given font size. */
public OurTree(int fontSize) {
   Font font = OurUtil.getVizFont().deriveFont((float)fontSize);
   OurTreeRenderer renderer = new OurTreeRenderer(fontSize);
   renderer.setFont(font);
   renderer.invalidate();
   renderer.validate();
   setRowHeight(0); // To allow variable row height on Mac OS X
   setCellRenderer(renderer);
   setFont(font);
   setBorder(new EmptyBorder(8, 8, 2, 2));
   getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
   putClientProperty("JTree.lineStyle", "Angled");
   setRootVisible(true);
   setForeground(Color.BLACK);
   setBackground(Color.WHITE);
   setOpaque(true);
   addTreeSelectionListener(new TreeSelectionListener() {
      public void valueChanged(TreeSelectionEvent e) {
         TreePath path = OurTree.this.getSelectionPath();
         if (path!=null) OurTree.this.listeners.fire(OurTree.this, Listener.Event.CLICK, path.getLastPathComponent());
      }
   });
}
 
Example 11
Project: incubator-netbeans   File: TreeView.java   Source Code and License 6 votes vote down vote up
@Override
public void valueChanged(TreeSelectionEvent ev) {
    TreePath[] paths = tree.getSelectionPaths();

    if (paths == null) {
        // part of bugfix #37279, if DnD is active then is useless select a nearby node
        if (ExplorerDnDManager.getDefault().isDnDActive()) {
            return;
        }

        callSelectionChanged(new Node[0]);
    } else {
        // we need to force no changes to nodes hierarchy =>
        // we are requesting read request, but it is not necessary
        // to execute the next action immediatelly, so postReadRequest
        // should be enough
        readAccessPaths = paths;
        Children.MUTEX.postReadRequest(this);
    }
}
 
Example 12
Project: Logisim   File: ProjectExplorer.java   Source Code and License 6 votes vote down vote up
@Override
public boolean canPerformAction(JTree targetTree, Object draggedNode, int action, Point location) {
	TreePath pathTarget = targetTree.getPathForLocation(location.x, location.y);
	if (pathTarget == null) {
		targetTree.setSelectionPath(null);
		return false;
	}
	targetTree.setSelectionPath(pathTarget);
	if (action == DnDConstants.ACTION_COPY) {
		return false;
	} else if (action == DnDConstants.ACTION_MOVE) {
		Object targetNode = pathTarget.getLastPathComponent();
		return canMove(draggedNode, targetNode);
	} else {
		return false;
	}
}
 
Example 13
Project: incubator-netbeans   File: TreeView.java   Source Code and License 6 votes vote down vote up
@Override
public void treeNodesRemoved(TreeModelEvent e) {
    // called to removed from JTree.expandedState
    super.treeNodesRemoved(e);
    
    boolean wasSelected = removedNodeWasSelected;
    removedNodeWasSelected = false;

    // part of bugfix #37279, if DnD is active then is useless select a nearby node
    if (ExplorerDnDManager.getDefault().isDnDActive()) {
        return;
    }
    if (wasSelected && tree.getSelectionCount() == 0) {
        TreePath path = findSiblingTreePath(e.getTreePath(), e.getChildIndices());

        // bugfix #39564, don't select again the same object
        if ((path == null) || e.getChildIndices().length == 0) {
            return;
        } else if (path.getPathCount() > 0) {
            tree.setSelectionPath(path);
        }
    }
}
 
Example 14
Project: featurea   File: SimulationTreePanel.java   Source Code and License 6 votes vote down vote up
/**
 * Applies a force to the given body if the user accepts the input.
 */
private void applyForceAction() {
    // the current selection should have the body selected
    TreePath path = this.tree.getSelectionPath();
    // make sure that something is selected
    if (path != null) {
        // getProperty the currently selected node
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
        // make sure the selected node is a body
        if (node.getUserObject() instanceof SandboxBody) {
            // getProperty the body from the node
            SandboxBody body = (SandboxBody) node.getUserObject();
            // show the force input dialog
            Vector2 f = ApplyForceDialog.show(ControlUtilities.getParentWindow(this));
            // make sure the user accepted the input
            if (f != null) {
                synchronized (Simulation.LOCK) {
                    body.applyForce(f);
                }
            }
        }
    }
}
 
Example 15
Project: jmt   File: TemplateAddingPanel.java   Source Code and License 6 votes vote down vote up
public AvailableTreeTable() {
	super();
	setTreeTableModel(new AvailableTreeTableModel(data.getRoot()));
	sizeColumns();
	setRowHeight(CELL_HEIGHT);
	setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
	getTableHeader().setReorderingAllowed(false);

	addTreeSelectionListener(new TreeSelectionListener() {
		@Override
		public void valueChanged(TreeSelectionEvent e) {
			TreePath path = e.getPath();
			TreeTableNode node = (TreeTableNode) path.getLastPathComponent();
			if ("template".equals(node.getType())) {
				tempDownload.setEnabled(true);
			} else {
				tempDownload.setEnabled(false);
			}
		}
	});
}
 
Example 16
Project: openjdk-jdk10   File: LastNodeLowerHalfDrop.java   Source Code and License 6 votes vote down vote up
private boolean haveCompleteNode(JTree tree) {
    int[] selRows = tree.getSelectionRows();
    TreePath path = tree.getPathForRow(selRows[0]);
    DefaultMutableTreeNode first = (DefaultMutableTreeNode)
            path.getLastPathComponent();
    int childCount = first.getChildCount();
    // first has children and no children are selected.
    if (childCount > 0 && selRows.length == 1) {
        return false;
    }
    // first may have children.
    for (int i = 1; i < selRows.length; i++) {
        path = tree.getPathForRow(selRows[i]);
        DefaultMutableTreeNode next = (DefaultMutableTreeNode)
                path.getLastPathComponent();
        if (first.isNodeChild(next)) {
            // Found a child of first.
            if (childCount > selRows.length - 1) {
                // Not all children of first are selected.
                return false;
            }
        }
    }
    return true;
}
 
Example 17
Project: rapidminer   File: ExtendedCheckTreeSelectionModel.java   Source Code and License 6 votes vote down vote up
private boolean areSiblingsSelected(TreePath path) {
	TreePath parent = path.getParentPath();
	if (parent == null) {
		return true;
	}
	Object node = path.getLastPathComponent();
	Object parentNode = parent.getLastPathComponent();

	int childCount = model.getChildCount(parentNode);
	for (int i = 0; i < childCount; i++) {
		Object childNode = model.getChild(parentNode, i);
		if (childNode == node) {
			continue;
		}
		if (!isPathSelected(parent.pathByAddingChild(childNode))) {
			return false;
		}
	}
	return true;
}
 
Example 18
Project: incubator-netbeans   File: TemplatesPanelGUI.java   Source Code and License 6 votes vote down vote up
/** Make a path visible.
* @param path the path
*/
private void showPathWithoutExpansion(TreePath path) {
    Rectangle rect = tree.getPathBounds(path);
    if (rect != null) { //PENDING
        TreeUI tmp = tree.getUI();
        int correction = 0;
        if (tmp instanceof BasicTreeUI) {
            correction = ((BasicTreeUI) tmp).getLeftChildIndent();
            correction += ((BasicTreeUI) tmp).getRightChildIndent();
        }
        rect.x = Math.max(0, rect.x - correction);
        rect.y += rect.height;
        if (rect.y >= 0) { //#197514 - do not scroll to negative y values
            tree.scrollRectToVisible(rect);
        }
    }
}
 
Example 19
Project: Logisim   File: ComponentSelector.java   Source Code and License 6 votes vote down vote up
public boolean hasSelectedItems() {
	TreePath[] sel = getSelectionPaths();
	if (sel == null || sel.length == 0)
		return false;

	for (int i = 0; i < sel.length; i++) {
		Object last = sel[i].getLastPathComponent();
		if (last instanceof OptionNode) {
			return true;
		} else if (last instanceof ComponentNode) {
			if (((ComponentNode) last).opts == null)
				return true;
		}
	}
	return false;
}
 
Example 20
Project: featurea   File: SimulationTreePanel.java   Source Code and License 6 votes vote down vote up
/**
 * Shows an edit body dialog.
 * <p>
 * If the user clicks the save button, the selected body is updated with the new values.
 */
private void editBodyAction() {
    // getProperty the currently selected body
    TreePath path = this.tree.getSelectionPath();
    // make sure something is selected
    if (path != null) {
        // getProperty the selected node
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
        // make sure its a body that is selected
        if (node.getUserObject() instanceof SandboxBody) {
            // getProperty the body from the node
            SandboxBody body = (SandboxBody) node.getUserObject();
            // pass the body to the edit dialog
            synchronized (Simulation.LOCK) {
                EditBodyDialog.show(ControlUtilities.getParentWindow(this), body);
            }
        }
    }
}
 
Example 21
Project: incubator-netbeans   File: PathsCustomizer.java   Source Code and License 6 votes vote down vote up
@Override
public void setSelectionPaths(TreePath[] treePaths) {
    ArrayList<TreePath> paths = new ArrayList<>(treePaths.length);
    for (TreePath treePath : treePaths) {
        Object lastPathComponent = treePath.getLastPathComponent();
        if (lastPathComponent instanceof DefaultMutableTreeNode) {
            Object obj = ((DefaultMutableTreeNode) lastPathComponent).getUserObject();
            if (obj != MODULEPATH && obj != CLASSPATH) {
                paths.add(treePath);
            }
        }
    }
    if (treePaths.length > 0 && paths.isEmpty()) {
        paths.addAll(Arrays.asList(getSelectionPaths()));
    }
    super.setSelectionPaths(paths.toArray(new TreePath[paths.size()]));
}
 
Example 22
Project: incubator-netbeans   File: EventBroadcaster.java   Source Code and License 6 votes vote down vote up
/**
 * Compute real table row indices of nodes that are affected by the event.
 *
 * @param e Event description.
 * @return Indices of rows in the table where the nodes (affected by the
 * event) are displayed, or null if they are not available.
 */
private int[] computeRowIndices(TreeModelEvent e) {
    int[] rowIndices;
    int parentRow = getLayout().getRowForPath(e.getTreePath());
    if (e.getChildren() != null) {
        rowIndices = new int[e.getChildren().length];
        for (int i = 0; i < e.getChildren().length; i++) {
            TreePath childPath =
                    e.getTreePath().pathByAddingChild(e.getChildren()[i]);
            int index = getLayout().getRowForPath(childPath);
            rowIndices[i] = index < 0
                    // child node is not shown yet, compute child row from
                    // parent row and index of the child
                    ? parentRow + e.getChildIndices()[i] + 1
                    : index;
        }
    } else {
        rowIndices = null;
    }
    return rowIndices;
}
 
Example 23
Project: incubator-netbeans   File: Outline.java   Source Code and License 6 votes vote down vote up
/** Set whether or not the root is visible */
public void setRootVisible (boolean val) {
    if (getOutlineModel() == null) {
        cachedRootVisible = val ? Boolean.TRUE : Boolean.FALSE;
    }
    if (val != isRootVisible()) {
        getLayoutCache().setRootVisible(val);
        if( getLayoutCache().getRowCount() > 0 ) {
            TreePath rootPath = getLayoutCache().getPathForRow(0);
            if( null != rootPath )
                getLayoutCache().treeStructureChanged(new TreeModelEvent(this, rootPath));
        }
        sortAndFilter();
        firePropertyChange("rootVisible", !val, val); //NOI18N
    }
}
 
Example 24
Project: rapidminer   File: PlotConfigurationTreeModel.java   Source Code and License 5 votes vote down vote up
private void dimensionConfigChanged(PlotConfigurationChangeEvent change) {
	PlotConfigurationTreeNode rootNode = (PlotConfigurationTreeNode) root;
	DimensionConfigChangeEvent dimensionChange = change.getDimensionChange();
	DimensionConfigTreeNode dimensionConfigNode = (DimensionConfigTreeNode) rootNode.getChild(dimensionChange
			.getDimension());

	nodeChanged(dimensionConfigNode);

	if (dimensionChange.getType() == DimensionConfigChangeType.COLUMN) {
		// change selection path
		TreePath path = new TreePath(getPathToRoot(dimensionConfigNode));
		makeVisibleAndSelect(path);
	}
}
 
Example 25
Project: JavaGraph   File: StateTree.java   Source Code and License 5 votes vote down vote up
private void maybeShowPopup(MouseEvent evt) {
    if (evt.isPopupTrigger()) {
        TreePath selectedPath = getPathForLocation(evt.getX(), evt.getY());
        TreeNode selectedNode =
            selectedPath == null ? null : (TreeNode) selectedPath.getLastPathComponent();
        StateTree.this.requestFocus();
        createPopupMenu(selectedNode).show(evt.getComponent(), evt.getX(), evt.getY());
    }
}
 
Example 26
Project: https-github.com-apache-zookeeper   File: ZooInspectorNodeViewersPanel.java   Source Code and License 5 votes vote down vote up
public void valueChanged(TreeSelectionEvent e) {
    TreePath[] paths = e.getPaths();
    selectedNodes.clear();
    for (TreePath path : paths) {
        boolean appended = false;
        StringBuilder sb = new StringBuilder();
        Object[] pathArray = path.getPath();
        for (Object o : pathArray) {
            if (o != null) {
                String nodeName = o.toString();
                if (nodeName != null) {
                    if (nodeName.length() > 0) {
                        appended = true;
                        sb.append("/"); //$NON-NLS-1$
                        sb.append(o.toString());
                    }
                }
            }
        }
        if (appended) {
            selectedNodes.add(sb.toString());
        }
    }
    for (int i = 0; i < needsReload.size(); i++) {
        this.needsReload.set(i, true);
    }
    reloadSelectedViewer();
}
 
Example 27
Project: scorekeeperfrontend   File: ClassTree.java   Source Code and License 5 votes vote down vote up
private void processSelection()
{
	TreePath tp = getSelectionPath();
	if (tp == null)
		return;

	DefaultMutableTreeNode lf = (DefaultMutableTreeNode)tp.getLastPathComponent();
	Object o = lf.getUserObject();
	if (o instanceof Entrant)
	{
		Entrant entrant = (Entrant)lf.getUserObject();
		Messenger.sendEvent(MT.CAR_ADD, entrant.getCarId());
	}
}
 
Example 28
Project: Logisim   File: ProjectExplorer.java   Source Code and License 5 votes vote down vote up
@Override
public void mouseClicked(MouseEvent e) {
	if (e.getClickCount() == 2) {
		TreePath path = getPathForLocation(e.getX(), e.getY());
		if (path != null && listener != null) {
			listener.doubleClicked(new Event(path));
		}
	}
}
 
Example 29
Project: truevfs   File: TFileTree.java   Source Code and License 5 votes vote down vote up
private TreePath substPath(
        final TreePath tp,
        final TreePath oldPath,
        final TreePath path) {
    final TFile file = (TFile) tp.getLastPathComponent();
    if (file.equals(oldPath.getLastPathComponent())) {
        return path;
    } else {
        final TreePath parent = substPath(tp.getParentPath(), oldPath, path);
        return parent.pathByAddingChild(
                new net.java.truevfs.access.TFile((TFile) parent.getLastPathComponent(),
                         file.getName()));
    }
}
 
Example 30
Project: marathonv5   File: JTreeJavaElement.java   Source Code and License 5 votes vote down vote up
private String getPathText(JTree tree, TreePath path) {
    Object lastPathComponent = path.getLastPathComponent();
    if (lastPathComponent == null) {
        return "";
    }
    return getTextForNodeObject(tree, lastPathComponent);
}
 
Example 31
Project: incubator-netbeans   File: Node.java   Source Code and License 5 votes vote down vote up
StringArraySubPathChooser(TreePath parentPath, String[] arr, int[] indices, JTreeOperator.StringComparator comparator) {
    this.arr = arr;
    this.comparator = comparator;
    this.indices = indices;
    this.parentPath = parentPath;
    this.parentPathCount = parentPath.getPathCount();
}
 
Example 32
Project: alevin-svn2   File: SelectionTreeItemListener.java   Source Code and License 5 votes vote down vote up
public SelectionTreeItemListener(SelectionPanel owner) {
	if (owner == null)
		throw new IllegalArgumentException();
	this.owner = owner;

	TreeModel model = owner.getTree().getModel();
	Object root = owner.getTree().getModel().getRoot();

	ePath = new TreePath(new Object[] { root, model.getChild(root, 0) });
	vPath = new TreePath(new Object[] { root, model.getChild(root, 1) });
}
 
Example 33
Project: rapidminer   File: GroupingConfigurationPanel.java   Source Code and License 5 votes vote down vote up
@Override
public void valueChanged(TreeSelectionEvent e) {
	TreePath newLeadSelectionPath = e.getNewLeadSelectionPath();
	if (newLeadSelectionPath != null) {
		if (newLeadSelectionPath.getLastPathComponent() instanceof DimensionConfigTreeNode) {
			adaptGUI();
		}
	}
}
 
Example 34
Project: freecol   File: DifficultyDialog.java   Source Code and License 5 votes vote down vote up
@Override
public void valueChanged(TreeSelectionEvent event) {
    TreePath path = event.getPath();
    if (path.getPathCount() >= 2) {
        DefaultMutableTreeNode node
            = (DefaultMutableTreeNode)path.getPathComponent(1);
        this.selected = (OptionGroup)node.getUserObject();
    }
}
 
Example 35
Project: incubator-netbeans   File: BindingCustomizer.java   Source Code and License 5 votes vote down vote up
@Override
public String pathToString(TreePath path) {
    StringBuilder sb = new StringBuilder();
    Object[] items = path.getPath();
    for (int i=1; i<items.length; i++) {
        sb.append(items[i]).append('.');
    }
    if (sb.length() > 0) {
        sb.deleteCharAt(sb.length()-1);
    }
    String value = sb.toString().trim();
    return "null".equals(value) ? "null" : designSupport.elWrap(sb.toString()); // NOI18N
}
 
Example 36
Project: incubator-netbeans   File: RegistryNode.java   Source Code and License 5 votes vote down vote up
public TreePath getTreePath() {
    List<RegistryNode> nodes = new LinkedList<RegistryNode>();
    
    RegistryNode node = this;
    while (node != null) {
        nodes.add(0, node);
        node = node.getParent();
    }
    
    return new TreePath(nodes.toArray());
}
 
Example 37
Project: incubator-netbeans   File: TreePathSupport.java   Source Code and License 5 votes vote down vote up
/**
    * Test if the tree path is visible (the parent path is expanded).
    * @param path The tree path to test
    * @return <code>true</code> if the path is visible, <code>false</code> otherwise.
    */
   public boolean isVisible(TreePath path) {
       if(path != null) {
    TreePath parentPath = path.getParentPath();

    if(parentPath != null) {
	return isExpanded(parentPath);
           }
    // Root.
    return true;
}
       return false;
   }
 
Example 38
Project: JAddOn   File: JTreeUtils.java   Source Code and License 5 votes vote down vote up
public static void expandPaths(JTree tree, ArrayList<String> paths_expanded) {
    for(int i = 0; i < tree.getRowCount(); i++) {
        TreePath tp = tree.getPathForRow(i);
        if(paths_expanded.contains(tp.toString())) {
            tree.expandRow(i);
        }
    }
}
 
Example 39
Project: Equella   File: WizardModel.java   Source Code and License 5 votes vote down vote up
/**
 * Notifies all listeners that have registered interest for notification on
 * this event type. The event instance is lazily created using the
 * parameters passed into the fire method.
 * 
 * @param source the node being changed
 * @param path the path to the root node
 * @param childIndices the indices of the changed elements
 * @param children the changed elements
 * @see EventListenerList
 */
private void fireTreeNodesInserted(TreePath path, int[] childIndices, Object[] children)
{
	TreeModelListener[] listeners = listenerList.getListeners(TreeModelListener.class);
	if( listeners != null && listeners.length > 0 )
	{
		TreeModelEvent e = new TreeModelEvent(this, path, childIndices, children);
		for( TreeModelListener listener : listeners )
		{
			listener.treeNodesInserted(e);
		}
	}
}
 
Example 40
Project: featurea   File: SimulationTreePanel.java   Source Code and License 5 votes vote down vote up
/**
 * Default constructor.
 */
public SimulationTreePanel() {
    this.root = new DefaultMutableTreeNode(null, true);
    this.model = new DefaultTreeModel(this.root);
    this.tree = new JTree(this.model);
    this.tree.setCellRenderer(new Renderer());
    this.tree.setEditable(false);
    this.tree.setShowsRootHandles(true);
    this.tree.setBorder(new EmptyBorder(5, 0, 0, 0));

    // the bounds
    this.bounds = new DefaultMutableTreeNode(new NullBounds());
    this.model.insertNodeInto(this.bounds, this.root, this.root.getChildCount());
    this.tree.expandPath(new TreePath(this.bounds).getParentPath());

    // folder to contain the bodies
    this.bodyFolder = new DefaultMutableTreeNode(Messages.getString("panel.tree.bodyFolder"));
    this.model.insertNodeInto(this.bodyFolder, this.root, this.root.getChildCount());
    this.tree.expandPath(new TreePath(this.bodyFolder.getPath()).getParentPath());

    // folder to contain the joints
    this.jointFolder = new DefaultMutableTreeNode(Messages.getString("panel.tree.jointFolder"));
    this.model.insertNodeInto(this.jointFolder, this.root, this.root.getChildCount());
    this.tree.expandPath(new TreePath(this.jointFolder.getPath()).getParentPath());

    // folder to contain the rays
    this.rayFolder = new DefaultMutableTreeNode(Messages.getString("panel.tree.rayFolder"));
    this.model.insertNodeInto(this.rayFolder, this.root, this.root.getChildCount());
    this.tree.expandPath(new TreePath(this.rayFolder.getPath()).getParentPath());

    this.scroller = new JScrollPane(this.tree);
    this.scroller.setBorder(BorderFactory.createLineBorder(Color.GRAY));

    this.setLayout(new BorderLayout());
    this.add(this.scroller);

    this.tree.addMouseListener(this);

    this.createContextMenus();
}
 
Example 41
Project: Equella   File: GroupsTab.java   Source Code and License 5 votes vote down vote up
private GroupTreeNode getSelectedGroupNode()
{
	TreePath selectionPath = tree.getSelectionPath();
	if( selectionPath != null )
	{
		return (GroupTreeNode) selectionPath.getLastPathComponent();
	}
	else
	{
		return null;
	}
}
 
Example 42
Project: call-IDE   File: FileNode.java   Source Code and License 5 votes vote down vote up
/**
 *  This method gets the parents tree of node
 *  @return tree path for node
 */
protected TreePath getTree()
{
    FileNode[] tempNodes;
    tempNodes = new FileNode[ file.path.length ];
    for (int i = 0 ; i < file.path.length ; i++)
    {
        tempNodes[i] = new FileNode( file.path[i]);
    }
    
    return new TreePath( tempNodes);
}
 
Example 43
Project: OpenJSharp   File: SynthTreeUI.java   Source Code and License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected void paintVerticalPartOfLeg(Graphics g,
                                      Rectangle clipBounds, Insets insets,
                                      TreePath path) {
    if (drawVerticalLines) {
        super.paintVerticalPartOfLeg(g, clipBounds, insets, path);
    }
}
 
Example 44
Project: featurea   File: RmlTagTreeTransferHandler.java   Source Code and License 5 votes vote down vote up
@Override
public boolean canImport(TransferHandler.TransferSupport transferSupport) {
    if (!transferSupport.isDrop()) {
        return false;
    }
    transferSupport.setShowDropLocation(true);
    if (!transferSupport.isDataFlavorSupported(myDataFlavor)) {
        return false;
    }
    JTree tree = (JTree) transferSupport.getComponent();
    int[] selectionRows = tree.getSelectionRows();

    // Do not allow a drop on the drag source selections.
    JTree.DropLocation dropLocation = (JTree.DropLocation) transferSupport.getDropLocation();
    int dropRow = tree.getRowForPath(dropLocation.getPath());
    if (Arrays.asList(selectionRows).contains(dropRow)) {
        return false;
    }

    // Do not allow MOVE-action drops if a non-leaf node is selected unless all of its children are also selected
    if (transferSupport.getDropAction() == MOVE) {
        return haveCompleteNode(tree);
    }

    // Do not allow a non-leaf node to be copied to a level which is less than its source level.
    TreePath destinationPath = dropLocation.getPath();
    DefaultMutableTreeNode target = (DefaultMutableTreeNode) destinationPath.getLastPathComponent();
    TreePath path = tree.getPathForRow(selectionRows[0]);
    DefaultMutableTreeNode firstNode = (DefaultMutableTreeNode) path.getLastPathComponent();
    if (firstNode.getChildCount() > 0 && target.getLevel() < firstNode.getLevel()) {
        return false;
    }
    return true;
}
 
Example 45
Project: incubator-netbeans   File: OutlineOperator.java   Source Code and License 5 votes vote down vote up
public void scrollToPath(TreePath irPath) {
    Point lrLocation = getLocationForPath(irPath);

    if (!lrLocation.equals(new Point(-1, -1))) {
        this.scrollToCell(lrLocation.y, lrLocation.x);
    }
}
 
Example 46
Project: incubator-netbeans   File: ManageInspectionsOperatot.java   Source Code and License 5 votes vote down vote up
public void checkInspections(String[] items) {
    for (String item : items) {
        JTreeOperator tree = new JTreeOperator(this);
        TreeNode[] treeNode = getPath(tree.getRoot(), "", item, false);
        TreePath treePath = new TreePath(treeNode);
        try {
            tree.clickOnPath(treePath);
            new EventTool().waitNoEvent(1000);
            tree.pushKey(KeyEvent.VK_SPACE);
            new EventTool().waitNoEvent(1000);
        } catch (Exception e) {
            throw e;
        }
    }
}
 
Example 47
Project: incubator-netbeans   File: Node.java   Source Code and License 5 votes vote down vote up
/**
 * creates new Node instance
 *
 * @param treeOperator JTreeOperator of tree where node lives
 * @param path TreePath of node
 */
public Node(JTreeOperator treeOperator, TreePath path) {
    // Only for plain JTreeOperator creates NodesJTreeOperator. If treeOperator
    // is something different (like TreeTableOperator$RenderedTreeOperator)
    // we cannot replace it.
    if (treeOperator.getClass().getName().endsWith("JTreeOperator")) {
        this.treeOperator = new NodesJTreeOperator(treeOperator);
    } else {
        this.treeOperator = treeOperator;
    }
    this.treePath = path;
    this.stringPath = convertPath(path);
}
 
Example 48
Project: featurea   File: SimulationTreePanel.java   Source Code and License 5 votes vote down vote up
/**
 * Shows a confirmation dialog asking the user if they really want to perform the action.
 * <p>
 * IF the user clicks yes, then the selected body is deleted.
 */
private void removeBodyAction() {
    // getProperty the currently selected body
    TreePath path = this.tree.getSelectionPath();
    // make sure something is selected
    if (path != null) {
        // getProperty the selected node
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
        // make sure its a body that is selected
        if (node.getUserObject() instanceof SandboxBody) {
            // getProperty the body from the node
            SandboxBody body = (SandboxBody) node.getUserObject();
            // make sure they are sure
            int choice = JOptionPane.showConfirmDialog(ControlUtilities.getParentWindow(this), MessageFormat
                            .format(Messages.getString("menu.resources.body.remove.warning"), body.getName()),
                    Messages.getString("menu.resources.body.remove.warning.title"),
                    JOptionPane.YES_NO_CANCEL_OPTION);
            // check the user's choice
            if (choice == JOptionPane.YES_OPTION) {
                // remove the body from the world
                synchronized (Simulation.LOCK) {
                    this.simulation.getWorld().removeBody(body);
                }
                // remove the node from the tree
                this.model.removeNodeFromParent(node);

                this.notifyActionListeners("remove-body", body);
            }
        }
    }
}
 
Example 49
Project: featurea   File: SimulationTreePanel.java   Source Code and License 5 votes vote down vote up
/**
 * Shows a confirmation message to make sure the user wants to proceed.
 * <p>
 * If the user accepts, the torque accumulator is cleared.
 */
private void clearTorqueAction() {
    // the current selection should have the body selected
    TreePath path = this.tree.getSelectionPath();
    // make sure that something is selected
    if (path != null) {
        // getProperty the currently selected node
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
        // make sure the selected node is a body
        if (node.getUserObject() instanceof SandboxBody) {
            // getProperty the body from the node
            SandboxBody body = (SandboxBody) node.getUserObject();
            // make sure they are sure
            int choice = JOptionPane.showConfirmDialog(ControlUtilities.getParentWindow(this), MessageFormat
                            .format(Messages.getString("menu.resources.body.clearTorque.warning"), body.getName()),
                    Messages.getString("menu.resources.body.clearTorque.warning.title"),
                    JOptionPane.YES_NO_CANCEL_OPTION);
            // check the user's choice
            if (choice == JOptionPane.YES_OPTION) {
                // clear only the force accumulator
                synchronized (Simulation.LOCK) {
                    body.clearAccumulatedTorque();
                }
            }
        }
    }
}
 
Example 50
Project: openjdk-jdk10   File: LastNodeLowerHalfDrop.java   Source Code and License 5 votes vote down vote up
@Override
public boolean importData(TransferHandler.TransferSupport support) {
    if (!canImport(support)) {
        return false;
    }
    // Extract transfer data.
    DefaultMutableTreeNode[] nodes = null;
    try {
        Transferable t = support.getTransferable();
        nodes = (DefaultMutableTreeNode[]) t.getTransferData(nodesFlavor);
    } catch (UnsupportedFlavorException ufe) {
        System.out.println("UnsupportedFlavor: " + ufe.getMessage());
    } catch (java.io.IOException ioe) {
        System.out.println("I/O error: " + ioe.getMessage());
    }
    // Get drop location info.
    JTree.DropLocation dl = (JTree.DropLocation) support.getDropLocation();
    int childIndex = dl.getChildIndex();
    TreePath dest = dl.getPath();
    DefaultMutableTreeNode parent = (DefaultMutableTreeNode)
            dest.getLastPathComponent();
    JTree tree = (JTree) support.getComponent();
    DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
    // Configure for drop mode.
    int index = childIndex;    // DropMode.INSERT
    if (childIndex == -1) {     // DropMode.ON
        index = parent.getChildCount();
    }
    // Add data to model.
    for (DefaultMutableTreeNode node : nodes) {
        model.insertNodeInto(node, parent, index++);
    }
    return true;
}
 
Example 51
Project: JavaGraph   File: LabelTree.java   Source Code and License 5 votes vote down vote up
/** Adds menu items for colouring and find/replace actions. */
private void addActionItems(JPopupMenu result) {
    TreePath[] selectedValues = getSelectionPaths();
    ActionStore actions = getJGraph().getActions();
    if (selectedValues != null && selectedValues.length == 1 && actions != null) {
        result.add(actions.getFindReplaceAction());
        if (getJGraph() instanceof AspectJGraph && actions.getSelectColorAction().isEnabled()) {
            result.add(actions.getSelectColorAction());
        }
        result.addSeparator();
    }
}
 
Example 52
Project: incubator-netbeans   File: TreeView.java   Source Code and License 5 votes vote down vote up
/** Synchronize the selected nodes from the manager of this Explorer.
* The default implementation does nothing.
*/
final void synchronizeSelectedNodes() {
    // run safely to be sure all preceding events are processed (especially VisualizerEvent.Added)
    // otherwise VisualizerNodes may not be in hierarchy yet (see #140629)
    VisualizerNode.runSafe(new Runnable() {
        @Override
        public void run() {
            Node[] arr = manager.getSelectedNodes();
            TreePath[] paths = new TreePath[arr.length];
            final boolean log = LOG.isLoggable(Level.FINE);
            if (log) {
                LOG.log(Level.FINE, "synchronizeSelectedNodes: {0}", arr.length);
            }
            for (int i = 0; i < arr.length; i++) {
                paths[i] = getTreePath(arr[i]);
                if (log) {
                    LOG.log(Level.FINE, "paths[{0}] = {1} node: {2}", new Object[]{i, paths[i], arr[i]});
                }
            }

            tree.getSelectionModel().removeTreeSelectionListener(managerListener);
            showSelection(paths);
            tree.getSelectionModel().addTreeSelectionListener(managerListener);
            if (log) {
                LOG.fine("synchronizeSelectedNodes done");
            }
        }
    });
}
 
Example 53
Project: incubator-netbeans   File: TreeView.java   Source Code and License 5 votes vote down vote up
void scrollTreeToVisible(TreePath path, TreeNode child) {
    Rectangle base = tree.getVisibleRect();
    Rectangle b1 = tree.getPathBounds(path);
    Rectangle b2 = tree.getPathBounds(new TreePath(treeModel.getPathToRoot(child)));

    if ((base != null) && (b1 != null) && (b2 != null)) {
        tree.scrollRectToVisible(new Rectangle(base.x, b1.y, 1, b2.y - b1.y + b2.height));
    }
}
 
Example 54
Project: incubator-netbeans   File: CheckTreeView.java   Source Code and License 5 votes vote down vote up
private void showPathWithoutExpansion(TreePath path) {
    Rectangle rect = tree.getPathBounds(path);

    if (rect != null && getWidth() > 0 && getHeight() > 0 ) {
        tree.scrollRectToVisible(rect);
    }
}
 
Example 55
Project: incubator-netbeans   File: TreeView.java   Source Code and License 5 votes vote down vote up
@Override
public void treeWillExpand(TreeExpansionEvent event)
throws ExpandVetoException {
    // prepare wait cursor and optionally show it
    TreePath path = event.getPath();
    prepareWaitCursor(DragDropUtilities.secureFindNode(path.getLastPathComponent()));
}
 
Example 56
Project: s-store   File: CatalogViewer.java   Source Code and License 5 votes vote down vote up
protected void highlight(Collection<DefaultMutableTreeNode> nodes) {
    // Collapse everything and then show the paths to each node
    for (int ctr = this.catalogTree.getRowCount(); ctr >= 0; ctr--) {
        if (this.catalogTree.isExpanded(ctr)) {
            this.catalogTree.collapseRow(ctr);              
        }
    } // FOR
    this.catalogTree.getSelectionModel().clearSelection();
    
    for (DefaultMutableTreeNode node : nodes) {
        TreePath path = new TreePath(node.getPath());
        this.catalogTree.setSelectionPath(path);
        this.catalogTree.expandPath(path);
    } // FOR
}
 
Example 57
Project: Equella   File: BrowseFinder.java   Source Code and License 5 votes vote down vote up
public String getSelectedParentGroup()
{
	TreePath selectionPath = tree.getSelectionPath();
	if( selectionPath != null )
	{
		return ((GroupNode) selectionPath.getLastPathComponent()).getId();
	}
	else
	{
		return null;
	}
}
 
Example 58
Project: truevfs   File: TFileTree.java   Source Code and License 5 votes vote down vote up
/**
 * Forwards the call to the {@link TFileTreeModel}
 * and scrolls the tree so that the successor to the deleted node
 * is selected and visible.
 * 
 * @throws IOException on any I/O error.
 */
public void rm(final TFile node) throws IOException {
    final TFileTreeModel ftm = getModel();
    final TreePath path = ftm.newTreePath(node);
    if (null == path)
        throw new IllegalArgumentException("node");
    scrollPathToVisible(path);
    final int row = getRowForPath(path);
    ftm.rm(node);
    setSelectionRow(row);
}
 
Example 59
Project: OpenJSharp   File: MultiTreeUI.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 60
Project: JAddOn   File: TreeTransferHandler.java   Source Code and License 5 votes vote down vote up
public boolean importData(TransferHandler.TransferSupport support) {
    if(!canImport(support)) {
        return false;
    }
    // Extract transfer data.
    DefaultMutableTreeNode[] nodes = null;
    try {
        Transferable t = support.getTransferable();
        nodes = (DefaultMutableTreeNode[])t.getTransferData(nodesFlavor);
    } catch(UnsupportedFlavorException ufe) {
        System.out.println("UnsupportedFlavor: " + ufe.getMessage());
    } catch(java.io.IOException ioe) {
        System.out.println("I/O error: " + ioe.getMessage());
    }
    // Get drop location info.
    JTree.DropLocation dl =
            (JTree.DropLocation)support.getDropLocation();
    int childIndex = dl.getChildIndex();
    TreePath dest = dl.getPath();
    DefaultMutableTreeNode parent =
        (DefaultMutableTreeNode)dest.getLastPathComponent();
    JTree tree = (JTree)support.getComponent();
    DefaultTreeModel model = (DefaultTreeModel)tree.getModel();
    // Configure for drop mode.
    int index = childIndex;    // DropMode.INSERT
    if(childIndex == -1) {     // DropMode.ON
        index = parent.getChildCount();
    }
    // Add data to model.
    for(int i = 0; i < nodes.length; i++) {
        model.insertNodeInto(nodes[i], parent, index++);
    }
    return true;
}