Java Code Examples for javax.swing.JTree#getPathForRow()

The following examples show how to use javax.swing.JTree#getPathForRow() . 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: MainFrameTree.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@SwingThread
void expandToFirstLeaf(int max) {
    Debug.println("expand to first leaf");
    if (leavesShown()) {
        return;
    }
    JTree jTree = getTree();
    int i = 0;
    while (true) {
        int rows = jTree.getRowCount();
        if (i >= rows || rows >= max) {
            break;
        }
        TreePath treePath = jTree.getPathForRow(i);
        Object lastPathComponent = treePath.getLastPathComponent();
        if (lastPathComponent instanceof BugLeafNode) {
            return;
        }
        jTree.expandRow(i++);
    }
}
 
Example 2
Source File: RTree.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
@Override
public String getText() {
    JTree tree = (JTree) component;
    if (row == -1) {
        return null;
    }
    TreePath rowPath = tree.getPathForRow(row);
    if (rowPath == null) {
        return null;
    }
    Object lastPathComponent = rowPath.getLastPathComponent();
    if (lastPathComponent != null) {
        return getTextForNodeObject(tree, lastPathComponent);
    }
    return null;
}
 
Example 3
Source File: RTree.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
private String getTextForNode(JTree tree, int row) {
    TreePath treePath = tree.getPathForRow(row);
    if (treePath == null) {
        return row + "";
    }
    StringBuilder sb = new StringBuilder();
    int start = tree.isRootVisible() ? 0 : 1;
    Object[] objs = treePath.getPath();
    for (int i = start; i < objs.length; i++) {
        String pathString;
        if (objs[i].toString() == null) {
            pathString = "";
        } else {
            pathString = escapeSpecialCharacters(getTextForNodeObject(tree, objs[i]));
        }
        sb.append("/" + pathString);
    }
    return sb.toString();
}
 
Example 4
Source File: RepositoryTreeUtil.java    From rapidminer-studio with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Expands all repositories and nodes, which have been saved before. Restores selected paths,
 * which have been saved proviously.
 *
 * @param tree
 *            The related tree, containing the path(s)
 */
public void restoreExpansionState(JTree tree) {
	List<TreePath> selectedPathList = new ArrayList<>();
	for (int i = 0; i < tree.getRowCount(); i++) {
		TreePath path = tree.getPathForRow(i);
		// sanity check for concurrent refreshes
		if (path != null) {
			Object entryObject = path.getLastPathComponent();
			if (entryObject instanceof Entry) {
				Entry entry = (Entry) entryObject;
				RepositoryLocation absoluteLocation = entry.getLocation();
				if (expandedNodes.contains(absoluteLocation)) {
					tree.expandPath(path);
				}
				if (selectedNodes.contains(absoluteLocation)) {
					selectedPathList.add(path);
				}
			}
		}
	}
	if (!selectedPathList.isEmpty()) {
		tree.setSelectionPaths(selectedPathList.toArray(new TreePath[0]));
	}
}
 
Example 5
Source File: CheckNodeListener.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void mousePressed(MouseEvent event) {
    JTree tree = (JTree) event.getSource();
    int x = event.getX();
    int y = event.getY();

    int row = tree.getRowForLocation(x, y);
    TreePath path = tree.getPathForRow(row);

    // if path exists and mouse is clicked exactly once
    if (path == null) {
        return;
    }
    CheckNode node = (CheckNode) path.getLastPathComponent();

    if ( !SwingUtilities.isRightMouseButton(event)) {
        return;
    }
    Object o = node.getUserObject();

}
 
Example 6
Source File: TreeHelpers.java    From binnavi with Apache License 2.0 6 votes vote down vote up
public static String getExpansionState(final JTree tree, final int row) {
  final TreePath rowPath = tree.getPathForRow(row);
  final StringBuffer buf = new StringBuffer();
  final int rowCount = tree.getRowCount();

  for (int i = row; i < rowCount; i++) {
    final TreePath path = tree.getPathForRow(i);
    if ((i == row) || isDescendant(path, rowPath)) {
      if (tree.isExpanded(path)) {
        buf.append(",");
        buf.append(String.valueOf(i - row));
      }
    } else {
      break;
    }
  }
  return buf.toString();
}
 
Example 7
Source File: RevertDeletedAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void mouseClicked(MouseEvent e) {
    JTree tree = (JTree) e.getSource();
    Point p = e.getPoint();
    int row = tree.getRowForLocation(e.getX(), e.getY());
    TreePath path = tree.getPathForRow(row);
    
    // if path exists and mouse is clicked exactly once
    if (path != null) {
        FileNode node = (FileNode) path.getLastPathComponent();
        Rectangle chRect = DeletedListRenderer.getCheckBoxRectangle();
        Rectangle rowRect = tree.getPathBounds(path);
        chRect.setLocation(chRect.x + rowRect.x, chRect.y + rowRect.y);
        if (e.getClickCount() == 1 && chRect.contains(p)) {
            boolean isSelected = !(node.isSelected());
            node.setSelected(isSelected);
            ((DefaultTreeModel) tree.getModel()).nodeChanged(node);
            if (row == 0) {
                tree.revalidate();
            }
            tree.repaint();
        }
    }
}
 
Example 8
Source File: View.java    From jpexs-decompiler with GNU General Public License v3.0 6 votes vote down vote up
public static List<List<String>> getExpandedNodes(JTree tree) {
    List<List<String>> expandedNodes = new ArrayList<>();
    int rowCount = tree.getRowCount();
    for (int i = 0; i < rowCount; i++) {
        try {
            TreePath path = tree.getPathForRow(i);
            if (tree.isExpanded(path)) {
                List<String> pathAsStringList = new ArrayList<>();
                for (Object pathCompnent : path.getPath()) {
                    pathAsStringList.add(pathCompnent.toString());
                }
                expandedNodes.add(pathAsStringList);
            }
        } catch (IndexOutOfBoundsException | NullPointerException ex) {
            // TreeNode was removed, ignore
        }
    }
    return expandedNodes;
}
 
Example 9
Source File: AbilityChooserTab.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e)
{
	if (!abilityCat.isEditable())
	{
		return;
	}

	Object data = availableTreeViewPanel.getSelectedObject();
	int index = categoryTable.getSelectedRow();
	if (data != null && data instanceof AbilityFacade && index != -1)
	{
		AbilityCategory category = (AbilityCategory) categoryTable.getValueAt(index, 0);
		character.addAbility(category, (AbilityFacade) data);
		availableTreeViewPanel.refilter();
		JTree tree = selectedTreeViewPanel.getTree();
		for (int i = 0; i < tree.getRowCount(); i++)
		{
			TreePath pathForRow = tree.getPathForRow(i);
			if (category.toString().equals(pathForRow.getLastPathComponent().toString()))
			{
				tree.expandRow(i);
			}
		}

	}
}
 
Example 10
Source File: CompanionInfoTab.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void selectCompanion(CompanionFacade compFacade)
{
	TreeTableModel treeTableModel = companionsTable.getTreeTableModel();
	treeTableModel.getRoot();
	TreePath path = null;

	JTree tree = companionsTable.getTree();
	String companionType = compFacade.getCompanionType();
	for (int i = 0; i < tree.getRowCount(); i++)
	{
		TreePath pathForRow = tree.getPathForRow(i);
		Object lastPathComponent = pathForRow.getLastPathComponent();
		if (lastPathComponent.toString().startsWith(companionType))
		{
			tree.expandRow(i);
		}
		else if (lastPathComponent instanceof pcgen.gui2.tabs.CompanionInfoTab.CompanionsModel.CompanionNode)
		{
			CompanionFacade rowComp =
				(CompanionFacade)
					((pcgen.gui2.tabs.CompanionInfoTab.CompanionsModel.CompanionNode) lastPathComponent)
						.getValueAt(0);

			if (rowComp != null && rowComp.getFileRef().get() == compFacade.getFileRef().get()
				&& rowComp.getNameRef().get() == compFacade.getNameRef().get()
				&& rowComp.getRaceRef().get() == compFacade.getRaceRef().get())
			{
				path = pathForRow;
			}
		}
	}
	if (path != null)
	{
		companionsTable.getTree().setSelectionPath(path);
		companionsTable.getTree().scrollPathToVisible(path);
	}
}
 
Example 11
Source File: MainFrameTree.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@SwingThread
boolean leavesShown() {
    JTree jTree = getTree();

    int rows = jTree.getRowCount();
    for (int i = 0; i < rows; i++) {
        TreePath treePath = jTree.getPathForRow(i);
        Object lastPathComponent = treePath.getLastPathComponent();
        if (lastPathComponent instanceof BugLeafNode) {
            return true;
        }
    }
    return false;
}
 
Example 12
Source File: LastNodeLowerHalfDrop.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
    if (!support.isDrop()) {
        return false;
    }
    support.setShowDropLocation(true);
    if (!support.isDataFlavorSupported(nodesFlavor)) {
        return false;
    }
    // Do not allow a drop on the drag source selections.
    JTree.DropLocation dl = (JTree.DropLocation) support.getDropLocation();
    JTree tree = (JTree) support.getComponent();
    int dropRow = tree.getRowForPath(dl.getPath());
    int[] selRows = tree.getSelectionRows();
    for (int i = 0; i < selRows.length; i++) {
        if (selRows[i] == dropRow) {
            return false;
        }
    }
    // Do not allow MOVE-action drops if a non-leaf node is
    // selected unless all of its children are also selected.
    int action = support.getDropAction();
    if (action == 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 dest = dl.getPath();
    DefaultMutableTreeNode target = (DefaultMutableTreeNode)
            dest.getLastPathComponent();
    TreePath path = tree.getPathForRow(selRows[0]);
    DefaultMutableTreeNode firstNode = (DefaultMutableTreeNode)
            path.getLastPathComponent();
    if (firstNode.getChildCount() > 0
            && target.getLevel() < firstNode.getLevel()) {
        return false;
    }
    return true;
}
 
Example 13
Source File: CheckTreeCellRenderer.java    From osp with GNU General Public License v3.0 5 votes vote down vote up
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
  Component renderer = delegate.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
  TreePath path = tree.getPathForRow(row);
  if(path!=null) {
    if(selectionModel.isPathOrAncestorSelected(path)) {
      checkBox.setState(TristateCheckBox.SELECTED);
    } else {
      checkBox.setState(selectionModel.isPathUnselected(path) ? TristateCheckBox.NOT_SELECTED : TristateCheckBox.PART_SELECTED);
    }
  }
  removeAll();
  add(checkBox, BorderLayout.WEST);
  add(renderer, BorderLayout.CENTER);
  return this;
}
 
Example 14
Source File: StoredObjectsTreeModel.java    From swift-explorer with Apache License 2.0 5 votes vote down vote up
public static void getTreeExpansionState (JTree tree, List<TreePath> list)
{
	if (list == null)
		return ;
	list.clear();
	if (tree == null)
		return ;
	for (int i = 0 ; i < tree.getRowCount() ; i++)
	{
		TreePath path = tree.getPathForRow(i) ;
		if (tree.isExpanded(path))
			list.add (path) ;
	}
}
 
Example 15
Source File: CheckNodeListener.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void mousePressed(MouseEvent event) {
    JTree tree = (JTree) event.getSource();
    int x = event.getX();
    int y = event.getY();

    int row = tree.getRowForLocation(x, y);
    TreePath path = tree.getPathForRow(row);

    // if path exists and mouse is clicked exactly once
    if (path == null) {
        return;
    }
    CheckNode node = (CheckNode) path.getLastPathComponent();

    if ( !SwingUtilities.isRightMouseButton(event)) {
        return;
    }
    Object o = node.getUserObject();

    if ( !(o instanceof TreeElement)) {
        return;
    }
    o = ((TreeElement) o).getUserObject();

    if (o instanceof RefactoringElement) {
        showPopup(((RefactoringElement) o).getLookup().lookupAll(Action.class), tree, x, y);
    }
}
 
Example 16
Source File: CheckListener.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void mouseClicked(MouseEvent e) {
    // todo (#pf): we need to solve problem between click and double
    // click - click should be possible only on the check box area
    // and double click should be bordered by title text.
    // we need a test how to detect where the mouse pointer is
    JTree tree = (JTree) e.getSource();
    Point p = e.getPoint();
    int x = e.getX();
    int y = e.getY();
    int row = tree.getRowForLocation(x, y);
    TreePath path = tree.getPathForRow(row);

    // if path exists and mouse is clicked exactly once
    if (path == null) {
        return;
    }

    Node node = Visualizer.findNode(path.getLastPathComponent());
    if (node == null) {
        return;
    }

    Rectangle chRect = CheckRenderer.getCheckBoxRectangle();
    Rectangle rowRect = tree.getPathBounds(path);
    chRect.setLocation(chRect.x + rowRect.x, chRect.y + rowRect.y);
    if (e.getClickCount() == 1 && chRect.contains(p)) {
        boolean isSelected = model.isNodeSelected(node);
        model.setNodeSelected(node, !isSelected);
        tree.repaint();
    }
}
 
Example 17
Source File: CheckNodeListener.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static void selectNextPrev(final boolean next, boolean isQuery, JTree tree) {
    int[] rows = tree.getSelectionRows();
    int newRow = rows == null || rows.length == 0 ? 0 : rows[0];
    int maxcount = tree.getRowCount();
    CheckNode node;
    do {
        if (next) {
            newRow++;
            if (newRow >= maxcount) {
                newRow = 0;
            }
        } else {
            newRow--;
            if (newRow < 0) {
                newRow = maxcount - 1;
            }
        }
        TreePath path = tree.getPathForRow(newRow);
        node = (CheckNode) path.getLastPathComponent();
        if (!node.isLeaf()) {
            tree.expandRow(newRow);
            maxcount = tree.getRowCount();
        }
    } while (!node.isLeaf());
    tree.setSelectionRow(newRow);
    tree.scrollRowToVisible(newRow);
}
 
Example 18
Source File: JTreeNodeJavaElement.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
public static Component getRendererComponent(JTree tree, int row) {
    TreeCellRenderer cellRenderer = tree.getCellRenderer();
    TreePath pathForRow = tree.getPathForRow(row);
    Object lastPathComponent = pathForRow.getLastPathComponent();
    Component rendererComponent = cellRenderer.getTreeCellRendererComponent(tree, lastPathComponent, false, false, false, row,
            false);
    if (rendererComponent == null) {
        return null;
    }
    if (rendererComponent instanceof JComponent) {
        ((JComponent) rendererComponent).putClientProperty("jtree", (JTree) tree);
        ((JComponent) rendererComponent).putClientProperty("row", row);
    }
    return rendererComponent;
}
 
Example 19
Source File: TreeKeyListener.java    From pumpernickel with MIT License 5 votes vote down vote up
@Override
protected boolean changeSelectionUsingText(KeyEvent e, String inputStr) {
	inputStr = inputStr.toUpperCase();
	JTree tree = (JTree) e.getComponent();

	int[] selection = tree.getSelectionRows();
	Arrays.sort(selection);
	int i = selection.length > 0 ? selection[selection.length - 1] : 0;
	int rowCount = tree.getRowCount();
	for (int offset = 0; offset < rowCount; offset++) {
		int row = (i + offset) % rowCount;
		TreePath path = tree.getPathForRow(row);
		TreeNode node = (TreeNode) path.getLastPathComponent();
		Component renderer = tree.getCellRenderer()
				.getTreeCellRendererComponent(tree, node, false,
						tree.isExpanded(path), node.isLeaf(), row,
						tree.isFocusOwner());
		String str = getText(renderer);
		if (str != null && str.length() >= 0
				&& str.toUpperCase().startsWith(inputStr)) {
			tree.setSelectionPath(path);
			return true;
		}
	}

	return false;
}
 
Example 20
Source File: GTreeState.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private LinkedHashSet<TreePath> getViewPaths(int limit) {

		Rectangle r = tree.getViewRect();
		JTree jTree = tree.getJTree();
		int top = jTree.getClosestRowForLocation(r.x, r.y);
		int bottom = jTree.getClosestRowForLocation(r.x, r.y + r.height);

		// JTree Note: the getClosestRowForLocation() call will return the row that is 
		//             closest to the point *and* that is not clipped.   So, when we get the 
		//             top and bottom values, the user can see more items at the edges past the
		//             top and bottom.   Lets compensate by adding 1 to both values so that the
		//             rows in the view contains all that the user can see.
		top -= 1;
		bottom += 1;

		//
		// 				Unusual Code Alert!
		//
		// Due to how the JTree scrolls, the best path to save is the bottom-most path.  When
		// you ask the tree to scroll to a path, it will only scroll until that path is just
		// in the view, which is at the bottom.  By saving the bottom-most, even if we don't 
		// save all of the view paths, the view will often appear unchanged, since by putting
		// the bottom path in the view, those paths above it may still be visible.
		//
		int end = bottom - limit;
		end = Math.max(end, top); // constrain 'end' when the limit is larger than the view size

		LinkedHashSet<TreePath> result = new LinkedHashSet<>();
		for (int i = bottom; i > end; i--) {
			TreePath path = jTree.getPathForRow(i);
			if (path == null) {
				// the top or bottom is out-of-range (can happen due to how we fudged the
				// 'top' and 'bottom' above)
				continue;
			}

			result.add(path);
		}
		return result;
	}