Java Utililty Methods JTree

List of utility methods to do JTree

Description

The list of methods to do JTree are organized into topic(s).

Method

DefaultMutableTreeNodepickFirstIfNone(JTree tree)
If an explicit pick has not been done then null will be returned.
DefaultMutableTreeNode result = null;
if (tree.isSelectionEmpty()) {
    tree.setSelectionRow(0);
if (tree.getSelectionCount() != 1) {
} else {
    TreePath treePath = tree.getSelectionPath();
    DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) treePath.getLastPathComponent();
...
voidprintComponentTree(final JComponent fc)
print Component Tree
printComponentTree(fc, "");
voidRemoveAll(JTree tree)
Remove All
RemoveChildren((DefaultMutableTreeNode) tree.getModel().getRoot());
tree.updateUI();
voidrepaintSelection(JTree tree)
Repaints the selection.
int[] selectedRows = tree.getSelectionRows();
if (selectedRows != null && selectedRows.length > 0) {
    Rectangle firstSelectedCell = tree.getRowBounds(selectedRows[0]);
    Rectangle lastSelectedCell = tree.getRowBounds(selectedRows[selectedRows.length - 1]);
    Rectangle repaintRectangle = firstSelectedCell.union(lastSelectedCell);
    repaintRectangle.x = 0;
    repaintRectangle.width = tree.getWidth();
    tree.repaint(repaintRectangle);
...
voidrestoreExpanstionState(JTree tree, int row, String expansionState)
restore Expanstion State
StringTokenizer stok = new StringTokenizer(expansionState, ",");
while (stok.hasMoreTokens()) {
    int token = row + Integer.parseInt(stok.nextToken());
    tree.expandRow(token);
voidrevalidateTree(java.awt.Component c)
revalidate Tree
if (c instanceof javax.swing.JComponent) {
    javax.swing.JComponent jc = (javax.swing.JComponent) c;
    jc.revalidate();
if (c instanceof java.awt.Container) {
    java.awt.Container container = (java.awt.Container) c;
    for (java.awt.Component component : container.getComponents()) {
        revalidateTree(component);
...
EnumerationsaveExpansionState(JTree tree)
Save the expansion state of a tree.
return tree.getExpandedDescendants(new TreePath(tree.getModel().getRoot()));
ArrayListsaveExpansionStateStrings(JTree tree)
save Expansion State Strings
ArrayList<String> result = new ArrayList<String>();
Enumeration<TreePath> expansionState = tree.getExpandedDescendants(new TreePath(tree.getModel().getRoot()));
if (expansionState != null) {
    while (expansionState.hasMoreElements()) {
        TreePath treePath = (TreePath) expansionState.nextElement();
        result.add(treePath.toString());
return result;
TreePath[]saveTreeSelection(JTree tree)
save Tree Selection
return tree == null ? null : tree.getSelectionPaths();
voidscrollToSelection(JTree tree)
scroll To Selection
if (!(tree.getParent() instanceof JViewport))
    return;
setViewPortPosition((JViewport) tree.getParent(), tree.getPathBounds(tree.getSelectionPath()));