FileDocCategorySizeDatePackage
JTree.javaAPI DocJava SE 6 API190989Tue Jun 10 00:26:40 BST 2008javax.swing

JTree

public class JTree extends JComponent implements Scrollable, Accessible
A control that displays a set of hierarchical data as an outline. You can find task-oriented documentation and examples of using trees in How to Use Trees, a section in The Java Tutorial.

A specific node in a tree can be identified either by a TreePath (an object that encapsulates a node and all of its ancestors), or by its display row, where each row in the display area displays one node. An expanded node is a non-leaf node (as identified by TreeModel.isLeaf(node) returning false) that will displays its children when all its ancestors are expanded. A collapsed node is one which hides them. A hidden node is one which is under a collapsed ancestor. All of a viewable nodes parents are expanded, but may or may not be displayed. A displayed node is both viewable and in the display area, where it can be seen.

The following JTree methods use "visible" to mean "displayed":

  • isRootVisible()
  • setRootVisible()
  • scrollPathToVisible()
  • scrollRowToVisible()
  • getVisibleRowCount()
  • setVisibleRowCount()

The next group of JTree methods use "visible" to mean "viewable" (under an expanded parent):

  • isVisible()
  • makeVisible()

If you are interested in knowing when the selection changes implement the TreeSelectionListener interface and add the instance using the method addTreeSelectionListener. valueChanged will be invoked when the selection changes, that is if the user clicks twice on the same node valueChanged will only be invoked once.

If you are interested in detecting either double-click events or when a user clicks on a node, regardless of whether or not it was selected, we recommend you do the following:

final JTree tree = ...;

MouseListener ml = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
if(selRow != -1) {
if(e.getClickCount() == 1) {
mySingleClick(selRow, selPath);
}
else if(e.getClickCount() == 2) {
myDoubleClick(selRow, selPath);
}
}
}
};
tree.addMouseListener(ml);
NOTE: This example obtains both the path and row, but you only need to get the one you're interested in.

To use JTree to display compound nodes (for example, nodes containing both a graphic icon and text), subclass {@link TreeCellRenderer} and use {@link #setCellRenderer} to tell the tree to use it. To edit such nodes, subclass {@link TreeCellEditor} and use {@link #setCellEditor}.

Like all JComponent classes, you can use {@link InputMap} and {@link ActionMap} to associate an {@link Action} object with a {@link KeyStroke} and execute the action under specified conditions.

Warning: Swing is not thread safe. For more information see Swing's Threading Policy.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see {@link java.beans.XMLEncoder}.

beaninfo
attribute: isContainer false description: A component that displays a set of hierarchical data as an outline.
version
1.196, 01/17/07
author
Rob Davis
author
Ray Ryan
author
Scott Violet

Fields Summary
private static final String
uiClassID
protected transient TreeModel
treeModel
The model that defines the tree displayed by this object.
protected transient TreeSelectionModel
selectionModel
Models the set of selected nodes in this tree.
protected boolean
rootVisible
True if the root node is displayed, false if its children are the highest visible nodes.
protected transient TreeCellRenderer
cellRenderer
The cell used to draw nodes. If null, the UI uses a default cellRenderer.
protected int
rowHeight
Height to use for each display row. If this is <= 0 the renderer determines the height for each row.
private boolean
rowHeightSet
private transient Hashtable
expandedState
Maps from TreePath to Boolean indicating whether or not the particular path is expanded. This ONLY indicates whether a given path is expanded, and NOT if it is visible or not. That information must be determined by visiting all the parent paths and seeing if they are visible.
protected boolean
showsRootHandles
True if handles are displayed at the topmost level of the tree.

A handle is a small icon that displays adjacent to the node which allows the user to click once to expand or collapse the node. A common interface shows a plus sign (+) for a node which can be expanded and a minus sign (-) for a node which can be collapsed. Handles are always shown for nodes below the topmost level.

If the rootVisible setting specifies that the root node is to be displayed, then that is the only node at the topmost level. If the root node is not displayed, then all of its children are at the topmost level of the tree. Handles are always displayed for nodes other than the topmost.

If the root node isn't visible, it is generally a good to make this value true. Otherwise, the tree looks exactly like a list, and users may not know that the "list entries" are actually tree nodes.

private boolean
showsRootHandlesSet
protected transient TreeSelectionRedirector
selectionRedirector
Creates a new event and passed it off the selectionListeners.
protected transient TreeCellEditor
cellEditor
Editor for the entries. Default is null (tree is not editable).
protected boolean
editable
Is the tree editable? Default is false.
protected boolean
largeModel
Is this tree a large model? This is a code-optimization setting. A large model can be used when the cell height is the same for all nodes. The UI will then cache very little information and instead continually message the model. Without a large model the UI caches most of the information, resulting in fewer method calls to the model.

This value is only a suggestion to the UI. Not all UIs will take advantage of it. Default value is false.

protected int
visibleRowCount
Number of rows to make visible at one time. This value is used for the Scrollable interface. It determines the preferred size of the display area.
protected boolean
invokesStopCellEditing
If true, when editing is to be stopped by way of selection changing, data in tree changing or other means stopCellEditing is invoked, and changes are saved. If false, cancelCellEditing is invoked, and changes are discarded. Default is false.
protected boolean
scrollsOnExpand
If true, when a node is expanded, as many of the descendants are scrolled to be visible.
private boolean
scrollsOnExpandSet
protected int
toggleClickCount
Number of mouse clicks before a node is expanded.
protected transient TreeModelListener
treeModelListener
Updates the expandedState.
private transient Stack
expandedStack
Used when setExpandedState is invoked, will be a Stack of Stacks.
private TreePath
leadPath
Lead selection path, may not be null.
private TreePath
anchorPath
Anchor path.
private boolean
expandsSelectedPaths
True if paths in the selection should be expanded.
private boolean
settingUI
This is set to true for the life of the setUI call.
private boolean
dragEnabled
If true, mouse presses on selections initiate a drag operation.
private DropMode
dropMode
The drop mode for this component.
private transient DropLocation
dropLocation
The drop location.
private int
expandRow
The row to expand during DnD.
private TreeTimer
dropTimer
A timer to expand nodes during drop.
private transient TreeExpansionListener
uiTreeExpansionListener
When addTreeExpansionListener is invoked, and settingUI is true, this ivar gets set to the passed in Listener. This listener is then notified first in fireTreeCollapsed and fireTreeExpanded.

This is an ugly workaround for a way to have the UI listener get notified before other listeners.

private static int
TEMP_STACK_SIZE
Max number of stacks to keep around.
public static final String
CELL_RENDERER_PROPERTY
Bound property name for cellRenderer.
public static final String
TREE_MODEL_PROPERTY
Bound property name for treeModel.
public static final String
ROOT_VISIBLE_PROPERTY
Bound property name for rootVisible.
public static final String
SHOWS_ROOT_HANDLES_PROPERTY
Bound property name for showsRootHandles.
public static final String
ROW_HEIGHT_PROPERTY
Bound property name for rowHeight.
public static final String
CELL_EDITOR_PROPERTY
Bound property name for cellEditor.
public static final String
EDITABLE_PROPERTY
Bound property name for editable.
public static final String
LARGE_MODEL_PROPERTY
Bound property name for largeModel.
public static final String
SELECTION_MODEL_PROPERTY
Bound property name for selectionModel.
public static final String
VISIBLE_ROW_COUNT_PROPERTY
Bound property name for visibleRowCount.
public static final String
INVOKES_STOP_CELL_EDITING_PROPERTY
Bound property name for messagesStopCellEditing.
public static final String
SCROLLS_ON_EXPAND_PROPERTY
Bound property name for scrollsOnExpand.
public static final String
TOGGLE_CLICK_COUNT_PROPERTY
Bound property name for toggleClickCount.
public static final String
LEAD_SELECTION_PATH_PROPERTY
Bound property name for leadSelectionPath.
public static final String
ANCHOR_SELECTION_PATH_PROPERTY
Bound property name for anchor selection path.
public static final String
EXPANDS_SELECTED_PATHS_PROPERTY
Bound property name for expands selected paths property
Constructors Summary
public JTree()
Returns a JTree with a sample model. The default model used by the tree defines a leaf node as any node without children.

see
DefaultTreeModel#asksAllowsChildren

        this(getDefaultTreeModel());
    
public JTree(Object[] value)
Returns a JTree with each element of the specified array as the child of a new root node which is not displayed. By default, the tree defines a leaf node as any node without children.

param
value an array of Objects
see
DefaultTreeModel#asksAllowsChildren

        this(createTreeModel(value));
        this.setRootVisible(false);
        this.setShowsRootHandles(true);
        expandRoot();
    
public JTree(Vector value)
Returns a JTree with each element of the specified Vector as the child of a new root node which is not displayed. By default, the tree defines a leaf node as any node without children.

param
value a Vector
see
DefaultTreeModel#asksAllowsChildren

        this(createTreeModel(value));
        this.setRootVisible(false);
        this.setShowsRootHandles(true);
        expandRoot();
    
public JTree(Hashtable value)
Returns a JTree created from a Hashtable which does not display with root. Each value-half of the key/value pairs in the HashTable becomes a child of the new root node. By default, the tree defines a leaf node as any node without children.

param
value a Hashtable
see
DefaultTreeModel#asksAllowsChildren

        this(createTreeModel(value));
        this.setRootVisible(false);
        this.setShowsRootHandles(true);
        expandRoot();
    
public JTree(TreeNode root)
Returns a JTree with the specified TreeNode as its root, which displays the root node. By default, the tree defines a leaf node as any node without children.

param
root a TreeNode object
see
DefaultTreeModel#asksAllowsChildren

        this(root, false);
    
public JTree(TreeNode root, boolean asksAllowsChildren)
Returns a JTree with the specified TreeNode as its root, which displays the root node and which decides whether a node is a leaf node in the specified manner.

param
root a TreeNode object
param
asksAllowsChildren if false, any node without children is a leaf node; if true, only nodes that do not allow children are leaf nodes
see
DefaultTreeModel#asksAllowsChildren

        this(new DefaultTreeModel(root, asksAllowsChildren));
    
public JTree(TreeModel newModel)
Returns an instance of JTree which displays the root node -- the tree is created using the specified data model.

param
newModel the TreeModel to use as the data model

        super();
	expandedStack = new Stack();
	toggleClickCount = 2;
	expandedState = new Hashtable();
        setLayout(null);
        rowHeight = 16;
        visibleRowCount = 20;
        rootVisible = true;
        selectionModel = new DefaultTreeSelectionModel();
        cellRenderer = null;
	scrollsOnExpand = true;
        setOpaque(true);
	expandsSelectedPaths = true;
        updateUI();
        setModel(newModel);
    
Methods Summary
public voidaddSelectionInterval(int index0, int index1)
Adds the paths between index0 and index1, inclusive, to the selection.

param
index0 an integer specifying a display row, where 0 is the first row in the display
param
index1 an integer specifying a second display row

        TreePath[]         paths = getPathBetweenRows(index0, index1);

        this.getSelectionModel().addSelectionPaths(paths);
    
public voidaddSelectionPath(javax.swing.tree.TreePath path)
Adds the node identified by the specified TreePath to the current selection. If any component of the path isn't viewable, and getExpandsSelectedPaths is true it is made viewable.

Note that JTree does not allow duplicate nodes to exist as children under the same parent -- each sibling must be a unique object.

param
path the TreePath to add

        getSelectionModel().addSelectionPath(path);
    
public voidaddSelectionPaths(javax.swing.tree.TreePath[] paths)
Adds each path in the array of paths to the current selection. If any component of any of the paths isn't viewable and getExpandsSelectedPaths is true, it is made viewable.

Note that JTree does not allow duplicate nodes to exist as children under the same parent -- each sibling must be a unique object.

param
paths an array of TreePath objects that specifies the nodes to add

	getSelectionModel().addSelectionPaths(paths);
    
public voidaddSelectionRow(int row)
Adds the path at the specified row to the current selection.

param
row an integer specifying the row of the node to add, where 0 is the first row in the display

        int[]      rows = { row };

        addSelectionRows(rows);
    
public voidaddSelectionRows(int[] rows)
Adds the paths at each of the specified rows to the current selection.

param
rows an array of ints specifying the rows to add, where 0 indicates the first row in the display

        TreeUI             ui = getUI();

        if(ui != null && rows != null) {
            int                  numRows = rows.length;
            TreePath[]           paths = new TreePath[numRows];

            for(int counter = 0; counter < numRows; counter++)
                paths[counter] = ui.getPathForRow(this, rows[counter]);
            addSelectionPaths(paths);
        }
    
public voidaddTreeExpansionListener(javax.swing.event.TreeExpansionListener tel)
Adds a listener for TreeExpansion events.

param
tel a TreeExpansionListener that will be notified when a tree node is expanded or collapsed (a "negative expansion")

	if (settingUI) {
	    uiTreeExpansionListener = tel;
	}
        listenerList.add(TreeExpansionListener.class, tel);
    
public voidaddTreeSelectionListener(javax.swing.event.TreeSelectionListener tsl)
Adds a listener for TreeSelection events.

param
tsl the TreeSelectionListener that will be notified when a node is selected or deselected (a "negative selection")

        listenerList.add(TreeSelectionListener.class,tsl);
        if(listenerList.getListenerCount(TreeSelectionListener.class) != 0
           && selectionRedirector == null) {
            selectionRedirector = new TreeSelectionRedirector();
            selectionModel.addTreeSelectionListener(selectionRedirector);
        }
    
public voidaddTreeWillExpandListener(javax.swing.event.TreeWillExpandListener tel)
Adds a listener for TreeWillExpand events.

param
tel a TreeWillExpandListener that will be notified when a tree node will be expanded or collapsed (a "negative expansion")

        listenerList.add(TreeWillExpandListener.class, tel);
    
private voidcancelDropTimer()

        if (dropTimer != null && dropTimer.isRunning()) {
            expandRow = -1;
            dropTimer.stop();
        }
    
public voidcancelEditing()
Cancels the current editing session. Has no effect if the tree isn't being edited.

        TreeUI                  tree = getUI();

        if(tree != null)
	    tree.cancelEditing(this);
    
public voidclearSelection()
Clears the selection.

        getSelectionModel().clearSelection();
    
protected voidclearToggledPaths()
Clears the cache of toggled tree paths. This does NOT send out any TreeExpansionListener events.

	 expandedState.clear();
     
public voidcollapsePath(javax.swing.tree.TreePath path)
Ensures that the node identified by the specified path is collapsed and viewable.

param
path the TreePath identifying a node

	setExpandedState(path, false);
    
public voidcollapseRow(int row)
Ensures that the node in the specified row is collapsed.

If row is < 0 or >= getRowCount this will have no effect.

param
row an integer specifying a display row, where 0 is the first row in the display

	collapsePath(getPathForRow(row));
    
public java.lang.StringconvertValueToText(java.lang.Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus)
Called by the renderers to convert the specified value to text. This implementation returns value.toString, ignoring all other arguments. To control the conversion, subclass this method and use any of the arguments you need.

param
value the Object to convert to text
param
selected true if the node is selected
param
expanded true if the node is expanded
param
leaf true if the node is a leaf node
param
row an integer specifying the node's display row, where 0 is the first row in the display
param
hasFocus true if the node has the focus
return
the String representation of the node's value

        if(value != null) {
            String sValue = value.toString();
            if (sValue != null) {
                return sValue;
            }
        }
        return "";
    
protected static javax.swing.tree.TreeModelcreateTreeModel(java.lang.Object value)
Returns a TreeModel wrapping the specified object. If the object is:
  • an array of Objects,
  • a Hashtable, or
  • a Vector
then a new root node is created with each of the incoming objects as children. Otherwise, a new root is created with the specified object as its value.

param
value the Object used as the foundation for the TreeModel
return
a TreeModel wrapping the specified object

        DefaultMutableTreeNode           root;

        if((value instanceof Object[]) || (value instanceof Hashtable) ||
           (value instanceof Vector)) {
            root = new DefaultMutableTreeNode("root");
            DynamicUtilTreeNode.createChildren(root, value);
        }
        else {
            root = new DynamicUtilTreeNode("root", value);
        }
        return new DefaultTreeModel(root, false);
    
protected javax.swing.event.TreeModelListenercreateTreeModelListener()
Creates and returns an instance of TreeModelHandler. The returned object is responsible for updating the expanded state when the TreeModel changes.

For more information on what expanded state means, see the JTree description above.

	 return new TreeModelHandler();
     
voiddndDone()
Called to indicate to this component that DnD is done. Allows for us to cancel the expand timer.

        cancelDropTimer();
        dropTimer = null;
    
javax.swing.JTree$DropLocationdropLocationForPoint(java.awt.Point p)
Calculates a drop location in this component, representing where a drop at the given point should insert data.

param
p the point to calculate a drop location for
return
the drop location, or null

        DropLocation location = null;

        int row = getClosestRowForLocation(p.x, p.y);
        Rectangle bounds = getRowBounds(row);
        TreeModel model = getModel();
        Object root = (model == null) ? null : model.getRoot();
        TreePath rootPath = (root == null) ? null : new TreePath(root);

        TreePath child = null;
        TreePath parent = null;
        boolean outside = row == -1
                          || p.y < bounds.y
                          || p.y >= bounds.y + bounds.height;

        switch(dropMode) {
            case USE_SELECTION:
            case ON:
                if (outside) {
                    location = new DropLocation(p, null, -1);
                } else {
                    location = new DropLocation(p, getPathForRow(row), -1);
                }

                break;
            case INSERT:
            case ON_OR_INSERT:
                if (row == -1) {
                    if (root != null && !model.isLeaf(root) && isExpanded(rootPath)) {
                        location = new DropLocation(p, rootPath, 0);                        
                    } else {
                        location = new DropLocation(p, null, -1);
                    }

                    break;
                }

                boolean checkOn = dropMode == DropMode.ON_OR_INSERT
                                  || !model.isLeaf(getPathForRow(row).getLastPathComponent());

                Section section = SwingUtilities2.liesInVertical(bounds, p, checkOn);
                if(section == LEADING) {
                    child = getPathForRow(row);
                    parent = child.getParentPath();
                } else if (section == TRAILING) {
                    int index = row + 1;
                    if (index >= getRowCount()) {
                        if (model.isLeaf(root) || !isExpanded(rootPath)) {
                            location = new DropLocation(p, null, -1);
                        } else {
                            parent = rootPath;
                            index = model.getChildCount(root);
                            location = new DropLocation(p, parent, index);
                        }

                        break;
                    }

                    child = getPathForRow(index);
                    parent = child.getParentPath();
                } else {
                    assert checkOn;
                    location = new DropLocation(p, getPathForRow(row), -1);
                    break;
                }

                if (parent != null) {
                    location = new DropLocation(p, parent,
                        model.getIndexOfChild(parent.getLastPathComponent(),
                                              child.getLastPathComponent()));
                } else if (checkOn || !model.isLeaf(root)) {
                    location = new DropLocation(p, rootPath, -1);
                } else {
                    location = new DropLocation(p, null, -1);
                }

                break;
            default:
                assert false : "Unexpected drop mode";
        }

        if (outside || row != expandRow) {
            cancelDropTimer();
        }

        if (!outside && row != expandRow) {
            if (isCollapsed(row)) {
                expandRow = row;
                startDropTimer();
            }
        }

        return location;
    
public voidexpandPath(javax.swing.tree.TreePath path)
Ensures that the node identified by the specified path is expanded and viewable. If the last item in the path is a leaf, this will have no effect.

param
path the TreePath identifying a node

	// Only expand if not leaf!
	TreeModel          model = getModel();

	if(path != null && model != null && 
	   !model.isLeaf(path.getLastPathComponent())) {
	    setExpandedState(path, true);
	}
    
private voidexpandRoot()
Expands the root path, assuming the current TreeModel has been set.

	TreeModel              model = getModel();

	if(model != null && model.getRoot() != null) {
	    expandPath(new TreePath(model.getRoot()));
	}
    
public voidexpandRow(int row)
Ensures that the node in the specified row is expanded and viewable.

If row is < 0 or >= getRowCount this will have no effect.

param
row an integer specifying a display row, where 0 is the first row in the display

	expandPath(getPathForRow(row));
    
public voidfireTreeCollapsed(javax.swing.tree.TreePath path)
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the path parameter.

param
path the TreePath indicating the node that was collapsed
see
EventListenerList

        // Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList();
        TreeExpansionEvent e = null;
	if (uiTreeExpansionListener != null) {
	    e = new TreeExpansionEvent(this, path);
	    uiTreeExpansionListener.treeCollapsed(e);
	}
        // Process the listeners last to first, notifying
        // those that are interested in this event
        for (int i = listeners.length-2; i>=0; i-=2) {
            if (listeners[i]==TreeExpansionListener.class &&
		listeners[i + 1] != uiTreeExpansionListener) {
                // Lazily create the event:
                if (e == null)
                    e = new TreeExpansionEvent(this, path);
                ((TreeExpansionListener)listeners[i+1]).
                    treeCollapsed(e);
            }          
        }
    
public voidfireTreeExpanded(javax.swing.tree.TreePath path)
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the path parameter.

param
path the TreePath indicating the node that was expanded
see
EventListenerList

        // Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList();
        TreeExpansionEvent e = null;
	if (uiTreeExpansionListener != null) {
	    e = new TreeExpansionEvent(this, path);
	    uiTreeExpansionListener.treeExpanded(e);
	}
        // Process the listeners last to first, notifying
        // those that are interested in this event
        for (int i = listeners.length-2; i>=0; i-=2) {
            if (listeners[i]==TreeExpansionListener.class &&
		listeners[i + 1] != uiTreeExpansionListener) {
                // Lazily create the event:
                if (e == null)
                    e = new TreeExpansionEvent(this, path);
                ((TreeExpansionListener)listeners[i+1]).
                    treeExpanded(e);
            }          
        }
    
public voidfireTreeWillCollapse(javax.swing.tree.TreePath path)
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the path parameter.

param
path the TreePath indicating the node that was expanded
see
EventListenerList

        // Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList();
        TreeExpansionEvent e = null;
        // Process the listeners last to first, notifying
        // those that are interested in this event
        for (int i = listeners.length-2; i>=0; i-=2) {
            if (listeners[i]==TreeWillExpandListener.class) {
                // Lazily create the event:
                if (e == null)
                    e = new TreeExpansionEvent(this, path);
                ((TreeWillExpandListener)listeners[i+1]).
                    treeWillCollapse(e);
            }          
        }
    
public voidfireTreeWillExpand(javax.swing.tree.TreePath path)
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the path parameter.

param
path the TreePath indicating the node that was expanded
see
EventListenerList

        // Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList();
        TreeExpansionEvent e = null;
        // Process the listeners last to first, notifying
        // those that are interested in this event
        for (int i = listeners.length-2; i>=0; i-=2) {
            if (listeners[i]==TreeWillExpandListener.class) {
                // Lazily create the event:
                if (e == null)
                    e = new TreeExpansionEvent(this, path);
                ((TreeWillExpandListener)listeners[i+1]).
                    treeWillExpand(e);
            }          
        }
    
protected voidfireValueChanged(javax.swing.event.TreeSelectionEvent e)
Notifies all listeners that have registered interest for notification on this event type.

param
e the TreeSelectionEvent to be fired; generated by the TreeSelectionModel when a node is selected or deselected
see
EventListenerList

        // Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList();
        // Process the listeners last to first, notifying
        // those that are interested in this event
        for (int i = listeners.length-2; i>=0; i-=2) {
            // TreeSelectionEvent e = null;
            if (listeners[i]==TreeSelectionListener.class) {
                // Lazily create the event:
                // if (e == null)
                // e = new ListSelectionEvent(this, firstIndex, lastIndex);
                ((TreeSelectionListener)listeners[i+1]).valueChanged(e);
            }          
        }
    
public javax.accessibility.AccessibleContextgetAccessibleContext()
Gets the AccessibleContext associated with this JTree. For JTrees, the AccessibleContext takes the form of an AccessibleJTree. A new AccessibleJTree instance is created if necessary.

return
an AccessibleJTree that serves as the AccessibleContext of this JTree

        if (accessibleContext == null) {
            accessibleContext = new AccessibleJTree();
        }
        return accessibleContext;
    
public javax.swing.tree.TreePathgetAnchorSelectionPath()
Returns the path identified as the anchor.

return
path identified as the anchor
since
1.3

	return anchorPath;
    
private java.lang.ObjectgetArchivableExpandedState()
Returns an object that can be archived indicating what nodes are expanded and what aren't. The objects from the model are NOT written out.

	TreeModel       model = getModel();

	if(model != null) {
	    Enumeration        paths = expandedState.keys();

	    if(paths != null) {
		Vector         state = new Vector();

		while(paths.hasMoreElements()) {
		    TreePath   path = (TreePath)paths.nextElement();
		    Object     archivePath;

		    try {
			archivePath = getModelIndexsForPath(path);
		    } catch (Error error) {
			archivePath = null;
		    }
		    if(archivePath != null) {
			state.addElement(archivePath);
			state.addElement(expandedState.get(path));
		    }
		}
		return state;
	    }
	}
	return null;
    
public javax.swing.tree.TreeCellEditorgetCellEditor()
Returns the editor used to edit entries in the tree.

return
the TreeCellEditor in use, or null if the tree cannot be edited

        return cellEditor;
    
public javax.swing.tree.TreeCellRenderergetCellRenderer()
Returns the current TreeCellRenderer that is rendering each cell.

return
the TreeCellRenderer that is rendering each cell

        return cellRenderer;
    
public javax.swing.tree.TreePathgetClosestPathForLocation(int x, int y)
Returns the path to the node that is closest to x,y. If no nodes are currently viewable, or there is no model, returns null, otherwise it always returns a valid path. To test if the node is exactly at x, y, get the node's bounds and test x, y against that.

param
x an integer giving the number of pixels horizontally from the left edge of the display area, minus any left margin
param
y an integer giving the number of pixels vertically from the top of the display area, minus any top margin
return
the TreePath for the node closest to that location, null if nothing is viewable or there is no model
see
#getPathForLocation
see
#getPathBounds

        TreeUI                  tree = getUI();

        if(tree != null)
            return tree.getClosestPathForLocation(this, x, y);
        return null;
    
public intgetClosestRowForLocation(int x, int y)
Returns the row to the node that is closest to x,y. If no nodes are viewable or there is no model, returns -1. Otherwise, it always returns a valid row. To test if the returned object is exactly at x, y, get the bounds for the node at the returned row and test x, y against that.

param
x an integer giving the number of pixels horizontally from the left edge of the display area, minus any left margin
param
y an integer giving the number of pixels vertically from the top of the display area, minus any top margin
return
the row closest to the location, -1 if nothing is viewable or there is no model
see
#getRowForLocation
see
#getRowBounds

	return getRowForPath(getClosestPathForLocation(x, y));
    
protected static javax.swing.tree.TreeModelgetDefaultTreeModel()
Creates and returns a sample TreeModel. Used primarily for beanbuilders to show something interesting.

return
the default TreeModel



                           
        
        DefaultMutableTreeNode      root = new DefaultMutableTreeNode("JTree");
	DefaultMutableTreeNode      parent;

	parent = new DefaultMutableTreeNode("colors");
	root.add(parent);
	parent.add(new DefaultMutableTreeNode("blue"));
	parent.add(new DefaultMutableTreeNode("violet"));
	parent.add(new DefaultMutableTreeNode("red"));
	parent.add(new DefaultMutableTreeNode("yellow"));

	parent = new DefaultMutableTreeNode("sports");
	root.add(parent);
	parent.add(new DefaultMutableTreeNode("basketball"));
	parent.add(new DefaultMutableTreeNode("soccer"));
	parent.add(new DefaultMutableTreeNode("football"));
	parent.add(new DefaultMutableTreeNode("hockey"));

	parent = new DefaultMutableTreeNode("food");
	root.add(parent);
	parent.add(new DefaultMutableTreeNode("hot dogs"));
	parent.add(new DefaultMutableTreeNode("pizza"));
	parent.add(new DefaultMutableTreeNode("ravioli"));
	parent.add(new DefaultMutableTreeNode("bananas"));
        return new DefaultTreeModel(root);
    
private javax.swing.tree.TreePath[]getDescendantSelectedPaths(javax.swing.tree.TreePath path, boolean includePath)
Returns an array of paths in the selection that are descendants of path. The returned array may contain nulls.

	TreeSelectionModel   sm = getSelectionModel();
	TreePath[]           selPaths = (sm != null) ? sm.getSelectionPaths() :
	                                null;

	if(selPaths != null) {
	    boolean        shouldRemove = false;

	    for(int counter = selPaths.length - 1; counter >= 0; counter--) {
		if(selPaths[counter] != null &&
		   path.isDescendant(selPaths[counter]) &&
		   (!path.equals(selPaths[counter]) || includePath))
		    shouldRemove = true;
		else
		    selPaths[counter] = null;
	    }
	    if(!shouldRemove) {
		selPaths = null;
	    }
	    return selPaths;
	}
	return null;
    
protected java.util.EnumerationgetDescendantToggledPaths(javax.swing.tree.TreePath parent)
Returns an Enumeration of TreePaths that have been expanded that are descendants of parent.

	if(parent == null)
	    return null;

	Vector            descendants = new Vector();
	Enumeration       nodes = expandedState.keys();
	TreePath          path;

	while(nodes.hasMoreElements()) {
	    path = (TreePath)nodes.nextElement();
	    if(parent.isDescendant(path))
		descendants.addElement(path);
	}
	return descendants.elements();
    
public booleangetDragEnabled()
Returns whether or not automatic drag handling is enabled.

return
the value of the {@code dragEnabled} property
see
#setDragEnabled
since
1.4

	return dragEnabled;
    
public final javax.swing.JTree$DropLocationgetDropLocation()
Returns the location that this component should visually indicate as the drop location during a DnD operation over the component, or {@code null} if no location is to currently be shown.

This method is not meant for querying the drop location from a {@code TransferHandler}, as the drop location is only set after the {@code TransferHandler}'s canImport has returned and has allowed for the location to be shown.

When this property changes, a property change event with name "dropLocation" is fired by the component.

return
the drop location
see
#setDropMode
see
TransferHandler#canImport(TransferHandler.TransferSupport)
since
1.6

        return dropLocation;
    
public final javax.swing.DropModegetDropMode()
Returns the drop mode for this component.

return
the drop mode for this component
see
#setDropMode
since
1.6

        return dropMode;
    
public javax.swing.tree.TreePathgetEditingPath()
Returns the path to the element that is currently being edited.

return
the TreePath for the node being edited

        TreeUI                  tree = getUI();

        if(tree != null)
            return tree.getEditingPath(this);
        return null;
    
public java.util.EnumerationgetExpandedDescendants(javax.swing.tree.TreePath parent)
Returns an Enumeration of the descendants of the path parent that are currently expanded. If parent is not currently expanded, this will return null. If you expand/collapse nodes while iterating over the returned Enumeration this may not return all the expanded paths, or may return paths that are no longer expanded.

param
parent the path which is to be examined
return
an Enumeration of the descendents of parent, or null if parent is not currently expanded

	if(!isExpanded(parent))
	    return null;

	Enumeration       toggledPaths = expandedState.keys();
	Vector            elements = null;
	TreePath          path;
	Object            value;

	if(toggledPaths != null) {
	    while(toggledPaths.hasMoreElements()) {
		path = (TreePath)toggledPaths.nextElement();
		value = expandedState.get(path);
		// Add the path if it is expanded, a descendant of parent,
		// and it is visible (all parents expanded). This is rather
		// expensive!
		if(path != parent && value != null &&
		   ((Boolean)value).booleanValue() &&
		   parent.isDescendant(path) && isVisible(path)) {
		    if (elements == null) {
			elements = new Vector();
		    }
		    elements.addElement(path);
		}
	    }
	}
	if (elements == null) {
	    Set<TreePath> empty = Collections.emptySet();
	    return Collections.enumeration(empty);
	}
	return elements.elements();
    
public booleangetExpandsSelectedPaths()
Returns the expandsSelectedPaths property.

return
true if selection changes result in the parent path being expanded
since
1.3
see
#setExpandsSelectedPaths

	return expandsSelectedPaths;
    
public booleangetInvokesStopCellEditing()
Returns the indicator that tells what happens when editing is interrupted.

return
the indicator that tells what happens when editing is interrupted
see
#setInvokesStopCellEditing

        return invokesStopCellEditing;
    
public java.lang.ObjectgetLastSelectedPathComponent()
Returns the last path component in the first node of the current selection.

return
the last Object in the first selected node's TreePath, or null if nothing is selected
see
TreePath#getLastPathComponent

        TreePath     selPath = getSelectionModel().getSelectionPath();

        if(selPath != null)
            return selPath.getLastPathComponent();
        return null;
    
public javax.swing.tree.TreePathgetLeadSelectionPath()
Returns the path identified as the lead.

return
path identified as the lead

	return leadPath;
    
public intgetLeadSelectionRow()
Returns the row index corresponding to the lead path.

return
an integer giving the row index of the lead path, where 0 is the first row in the display; or -1 if leadPath is null

	TreePath leadPath = getLeadSelectionPath();

	if (leadPath != null) {
	    return getRowForPath(leadPath);
	}
        return -1;
    
public intgetMaxSelectionRow()
Returns the last selected row.

return
an integer designating the last selected row, where 0 is the first row in the display

        return getSelectionModel().getMaxSelectionRow();
    
public intgetMinSelectionRow()
Gets the first selected row.

return
an integer designating the first selected row, where 0 is the first row in the display

        return getSelectionModel().getMinSelectionRow();
    
public javax.swing.tree.TreeModelgetModel()
Returns the TreeModel that is providing the data.

return
the TreeModel that is providing the data

        return treeModel;
    
private int[]getModelIndexsForPath(javax.swing.tree.TreePath path)
Returns an array of integers specifying the indexs of the components in the path. If path is the root, this will return an empty array. If path is null, null will be returned.

	if(path != null) {
	    TreeModel   model = getModel();
	    int         count = path.getPathCount();
	    int[]       indexs = new int[count - 1];
	    Object      parent = model.getRoot();

	    for(int counter = 1; counter < count; counter++) {
		indexs[counter - 1] = model.getIndexOfChild
			           (parent, path.getPathComponent(counter));
		parent = path.getPathComponent(counter);
		if(indexs[counter - 1] < 0)
		    return null;
	    }
	    return indexs;
	}
	return null;
    
public javax.swing.tree.TreePathgetNextMatch(java.lang.String prefix, int startingRow, javax.swing.text.Position$Bias bias)
Returns the TreePath to the next tree element that begins with a prefix. To handle the conversion of a TreePath into a String, convertValueToText is used.

param
prefix the string to test for a match
param
startingRow the row for starting the search
param
bias the search direction, either Position.Bias.Forward or Position.Bias.Backward.
return
the TreePath of the next tree element that starts with the prefix; otherwise null
exception
IllegalArgumentException if prefix is null or startingRow is out of bounds
since
1.4


        int max = getRowCount();
	if (prefix == null) {
	    throw new IllegalArgumentException();
	}
	if (startingRow < 0 || startingRow >= max) {
	    throw new IllegalArgumentException();
	}
	prefix = prefix.toUpperCase();

	// start search from the next/previous element froom the 
	// selected element
	int increment = (bias == Position.Bias.Forward) ? 1 : -1;
	int row = startingRow;
	do {
	    TreePath path = getPathForRow(row);
	    String text = convertValueToText(
	        path.getLastPathComponent(), isRowSelected(row),
		isExpanded(row), true, row, false);
	    
	    if (text.toUpperCase().startsWith(prefix)) {
		return path;
	    }
	    row = (row + increment + max) % max;
	} while (row != startingRow);
	return null;
    
protected javax.swing.tree.TreePath[]getPathBetweenRows(int index0, int index1)
Returns JTreePath instances representing the path between index0 and index1 (including index1). Returns null if there is no tree.

param
index0 an integer specifying a display row, where 0 is the first row in the display
param
index1 an integer specifying a second display row
return
an array of TreePath objects, one for each node between index0 and index1, inclusive; or null if there is no tree

        int              newMinIndex, newMaxIndex;
        TreeUI           tree = getUI();

        newMinIndex = Math.min(index0, index1);
        newMaxIndex = Math.max(index0, index1);

        if(tree != null) {
            TreePath[]            selection = new TreePath[newMaxIndex -
                                                            newMinIndex + 1];

            for(int counter = newMinIndex; counter <= newMaxIndex; counter++)
                selection[counter - newMinIndex] = tree.getPathForRow(this,
								      counter);
            return selection;
        }
        return null;
    
public java.awt.RectanglegetPathBounds(javax.swing.tree.TreePath path)
Returns the Rectangle that the specified node will be drawn into. Returns null if any component in the path is hidden (under a collapsed parent).

Note:
This method returns a valid rectangle, even if the specified node is not currently displayed.

param
path the TreePath identifying the node
return
the Rectangle the node is drawn in, or null

        TreeUI                   tree = getUI();

        if(tree != null)
            return tree.getPathBounds(this, path);
        return null;
    
private javax.swing.tree.TreePathgetPathForIndexs(int[] indexs)
Returns a TreePath created by obtaining the children for each of the indices in indexs. If indexs or the TreeModel is null, it will return null.

	if(indexs == null)
	    return null;

	TreeModel    model = getModel();

	if(model == null)
	    return null;

	int          count = indexs.length;
	Object       parent = model.getRoot();
	TreePath     parentPath = new TreePath(parent);

	for(int counter = 0; counter < count; counter++) {
	    parent = model.getChild(parent, indexs[counter]);
	    if(parent == null)
		return null;
	    parentPath = parentPath.pathByAddingChild(parent);
	}
	return parentPath;
    
public javax.swing.tree.TreePathgetPathForLocation(int x, int y)
Returns the path for the node at the specified location.

param
x an integer giving the number of pixels horizontally from the left edge of the display area, minus any left margin
param
y an integer giving the number of pixels vertically from the top of the display area, minus any top margin
return
the TreePath for the node at that location

        TreePath          closestPath = getClosestPathForLocation(x, y);

        if(closestPath != null) {
            Rectangle       pathBounds = getPathBounds(closestPath);

            if(pathBounds != null &&
               x >= pathBounds.x && x < (pathBounds.x + pathBounds.width) &&
               y >= pathBounds.y && y < (pathBounds.y + pathBounds.height))
                return closestPath;
        }
        return null;
    
public javax.swing.tree.TreePathgetPathForRow(int row)
Returns the path for the specified row. If row is not visible, null is returned.

param
row an integer specifying a row
return
the TreePath to the specified node, null if row < 0 or row > getRowCount()

        TreeUI                  tree = getUI();

        if(tree != null)
            return tree.getPathForRow(this, row);
        return null;
    
public java.awt.DimensiongetPreferredScrollableViewportSize()
Returns the preferred display size of a JTree. The height is determined from getVisibleRowCount and the width is the current preferred width.

return
a Dimension object containing the preferred size

        int                 width = getPreferredSize().width;
        int                 visRows = getVisibleRowCount();
        int                 height = -1;

        if(isFixedRowHeight())
            height = visRows * getRowHeight();
        else {
            TreeUI          ui = getUI();

            if (ui != null && visRows > 0) {
                int rc = ui.getRowCount(this);

                if (rc >= visRows) {
                    Rectangle bounds = getRowBounds(visRows - 1);
                    if (bounds != null) {
                        height = bounds.y + bounds.height;
                    }
                }
                else if (rc > 0) {
                    Rectangle bounds = getRowBounds(0);
                    if (bounds != null) {
                        height = bounds.height * visRows;
                    }
                }
            }
            if (height == -1) {
                height = 16 * visRows;
            }
        }
        return new Dimension(width, height);
    
public java.awt.RectanglegetRowBounds(int row)
Returns the Rectangle that the node at the specified row is drawn in.

param
row the row to be drawn, where 0 is the first row in the display
return
the Rectangle the node is drawn in

	return getPathBounds(getPathForRow(row));
    
public intgetRowCount()
Returns the number of rows that are currently being displayed.

return
the number of rows that are being displayed

        TreeUI            tree = getUI();

        if(tree != null)
            return tree.getRowCount(this);
        return 0;
    
public intgetRowForLocation(int x, int y)
Returns the row for the specified location.

param
x an integer giving the number of pixels horizontally from the left edge of the display area, minus any left margin
param
y an integer giving the number of pixels vertically from the top of the display area, minus any top margin
return
the row corresponding to the location, or -1 if the location is not within the bounds of a displayed cell
see
#getClosestRowForLocation

	return getRowForPath(getPathForLocation(x, y));
    
public intgetRowForPath(javax.swing.tree.TreePath path)
Returns the row that displays the node identified by the specified path.

param
path the TreePath identifying a node
return
an integer specifying the display row, where 0 is the first row in the display, or -1 if any of the elements in path are hidden under a collapsed parent.

        TreeUI                  tree = getUI();

        if(tree != null)
            return tree.getRowForPath(this, path);
        return -1;
    
public intgetRowHeight()
Returns the height of each row. If the returned value is less than or equal to 0 the height for each row is determined by the renderer.

        return rowHeight;
    
public intgetScrollableBlockIncrement(java.awt.Rectangle visibleRect, int orientation, int direction)
Returns the amount for a block increment, which is the height or width of visibleRect, based on orientation.

param
visibleRect the view area visible within the viewport
param
orientation either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL
param
direction less than zero to scroll up/left, greater than zero for down/right.
return
the "block" increment for scrolling in the specified direction
see
JScrollBar#setBlockIncrement(int)

        return (orientation == SwingConstants.VERTICAL) ? visibleRect.height :
            visibleRect.width;
    
public booleangetScrollableTracksViewportHeight()
Returns false to indicate that the height of the viewport does not determine the height of the table, unless the preferred height of the tree is smaller than the viewports height. In other words: ensure that the tree is never smaller than its viewport.

return
false
see
Scrollable#getScrollableTracksViewportHeight

	if (getParent() instanceof JViewport) {
	    return (((JViewport)getParent()).getHeight() > getPreferredSize().height);
	}
	return false;
    
public booleangetScrollableTracksViewportWidth()
Returns false to indicate that the width of the viewport does not determine the width of the table, unless the preferred width of the tree is smaller than the viewports width. In other words: ensure that the tree is never smaller than its viewport.

return
false
see
Scrollable#getScrollableTracksViewportWidth

	if (getParent() instanceof JViewport) {
	    return (((JViewport)getParent()).getWidth() > getPreferredSize().width);
	}
	return false;
    
public intgetScrollableUnitIncrement(java.awt.Rectangle visibleRect, int orientation, int direction)
Returns the amount to increment when scrolling. The amount is the height of the first displayed row that isn't completely in view or, if it is totally displayed, the height of the next row in the scrolling direction.

param
visibleRect the view area visible within the viewport
param
orientation either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL
param
direction less than zero to scroll up/left, greater than zero for down/right
return
the "unit" increment for scrolling in the specified direction
see
JScrollBar#setUnitIncrement(int)

        if(orientation == SwingConstants.VERTICAL) {
            Rectangle       rowBounds;
            int             firstIndex = getClosestRowForLocation
                                         (0, visibleRect.y);

            if(firstIndex != -1) {
                rowBounds = getRowBounds(firstIndex);
                if(rowBounds.y != visibleRect.y) {
                    if(direction < 0) {
                        // UP
                        return Math.max(0, (visibleRect.y - rowBounds.y));
                    }
                    return (rowBounds.y + rowBounds.height - visibleRect.y);
                }
                if(direction < 0) { // UP
                    if(firstIndex != 0) {
                        rowBounds = getRowBounds(firstIndex - 1);
                        return rowBounds.height;
                    }
                }
                else {
                    return rowBounds.height;
                }
            }
            return 0;
        }
        return 4;
    
public booleangetScrollsOnExpand()
Returns the value of the scrollsOnExpand property.

return
the value of the scrollsOnExpand property

	return scrollsOnExpand;
    
public intgetSelectionCount()
Returns the number of nodes selected.

return
the number of nodes selected

        return selectionModel.getSelectionCount();
    
public javax.swing.tree.TreeSelectionModelgetSelectionModel()
Returns the model for selections. This should always return a non-null value. If you don't want to allow anything to be selected set the selection model to null, which forces an empty selection model to be used.

see
#setSelectionModel

        return selectionModel;
    
public javax.swing.tree.TreePathgetSelectionPath()
Returns the path to the first selected node.

return
the TreePath for the first selected node, or null if nothing is currently selected

        return getSelectionModel().getSelectionPath();
    
public javax.swing.tree.TreePath[]getSelectionPaths()
Returns the paths of all selected values.

return
an array of TreePath objects indicating the selected nodes, or null if nothing is currently selected

        return getSelectionModel().getSelectionPaths();
    
public int[]getSelectionRows()
Returns all of the currently selected rows. This method is simply forwarded to the TreeSelectionModel. If nothing is selected null or an empty array will be returned, based on the TreeSelectionModel implementation.

return
an array of integers that identifies all currently selected rows where 0 is the first row in the display

        return getSelectionModel().getSelectionRows();
    
public booleangetShowsRootHandles()
Returns the value of the showsRootHandles property.

return
the value of the showsRootHandles property
see
#showsRootHandles

        return showsRootHandles;
    
public intgetToggleClickCount()
Returns the number of mouse clicks needed to expand or close a node.

return
number of mouse clicks before node is expanded
since
1.3

	return toggleClickCount;
    
public java.lang.StringgetToolTipText(java.awt.event.MouseEvent event)
Overrides JComponent's getToolTipText method in order to allow renderer's tips to be used if it has text set.

NOTE: For JTree to properly display tooltips of its renderers, JTree must be a registered component with the ToolTipManager. This can be done by invoking ToolTipManager.sharedInstance().registerComponent(tree). This is not done automatically!

param
event the MouseEvent that initiated the ToolTip display
return
a string containing the tooltip or null if event is null

        String tip = null;

        if(event != null) {
            Point p = event.getPoint();
            int selRow = getRowForLocation(p.x, p.y);
            TreeCellRenderer       r = getCellRenderer();

            if(selRow != -1 && r != null) {
                TreePath     path = getPathForRow(selRow);
                Object       lastPath = path.getLastPathComponent();
                Component    rComponent = r.getTreeCellRendererComponent
                    (this, lastPath, isRowSelected(selRow),
                     isExpanded(selRow), getModel().isLeaf(lastPath), selRow,
                     true);

                if(rComponent instanceof JComponent) {
                    MouseEvent      newEvent;
                    Rectangle       pathBounds = getPathBounds(path);

                    p.translate(-pathBounds.x, -pathBounds.y);
                    newEvent = new MouseEvent(rComponent, event.getID(),
                                          event.getWhen(),
                                              event.getModifiers(),
                                              p.x, p.y,
                                              event.getXOnScreen(),
                                              event.getYOnScreen(),
                                              event.getClickCount(),
                                              event.isPopupTrigger(),
                                              MouseEvent.NOBUTTON);
                    
                    tip = ((JComponent)rComponent).getToolTipText(newEvent);
                }
            }
        }
        // No tip from the renderer get our own tip
        if (tip == null) {
            tip = getToolTipText();
	}
        return tip;
    
public javax.swing.event.TreeExpansionListener[]getTreeExpansionListeners()
Returns an array of all the TreeExpansionListeners added to this JTree with addTreeExpansionListener().

return
all of the TreeExpansionListeners added or an empty array if no listeners have been added
since
1.4

        return (TreeExpansionListener[])listenerList.getListeners(
                TreeExpansionListener.class);
    
public javax.swing.event.TreeSelectionListener[]getTreeSelectionListeners()
Returns an array of all the TreeSelectionListeners added to this JTree with addTreeSelectionListener().

return
all of the TreeSelectionListeners added or an empty array if no listeners have been added
since
1.4

        return (TreeSelectionListener[])listenerList.getListeners(
                TreeSelectionListener.class);
    
public javax.swing.event.TreeWillExpandListener[]getTreeWillExpandListeners()
Returns an array of all the TreeWillExpandListeners added to this JTree with addTreeWillExpandListener().

return
all of the TreeWillExpandListeners added or an empty array if no listeners have been added
since
1.4

        return (TreeWillExpandListener[])listenerList.getListeners(
                TreeWillExpandListener.class);
    
public javax.swing.plaf.TreeUIgetUI()
Returns the L&F object that renders this component.

return
the TreeUI object that renders this component

        return (TreeUI)ui;
    
public java.lang.StringgetUIClassID()
Returns the name of the L&F class that renders this component.

return
the string "TreeUI"
see
JComponent#getUIClassID
see
UIDefaults#getUI

        return uiClassID;
    
public intgetVisibleRowCount()
Returns the number of rows that are displayed in the display area.

return
the number of rows displayed

        return visibleRowCount;
    
public booleanhasBeenExpanded(javax.swing.tree.TreePath path)
Returns true if the node identified by the path has ever been expanded.

return
true if the path has ever been expanded

	return (path != null && expandedState.get(path) != null);
    
public booleanisCollapsed(javax.swing.tree.TreePath path)
Returns true if the value identified by path is currently collapsed, this will return false if any of the values in path are currently not being displayed.

param
path the TreePath to check
return
true if any of the nodes in the node's path are collapsed, false if all nodes in the path are expanded

	return !isExpanded(path);
    
public booleanisCollapsed(int row)
Returns true if the node at the specified display row is collapsed.

param
row the row to check, where 0 is the first row in the display
return
true if the node is currently collapsed, otherwise false

	return !isExpanded(row);
    
public booleanisEditable()
Returns true if the tree is editable.

return
true if the tree is editable

        return editable;
    
public booleanisEditing()
Returns true if the tree is being edited. The item that is being edited can be obtained using getSelectionPath.

return
true if the user is currently editing a node
see
#getSelectionPath

        TreeUI                  tree = getUI();

        if(tree != null)
            return tree.isEditing(this);
        return false;
    
public booleanisExpanded(javax.swing.tree.TreePath path)
Returns true if the node identified by the path is currently expanded,

param
path the TreePath specifying the node to check
return
false if any of the nodes in the node's path are collapsed, true if all nodes in the path are expanded

	if(path == null)
	    return false;

	// Is this node expanded?
	Object          value = expandedState.get(path);

	if(value == null || !((Boolean)value).booleanValue())
	    return false;

	// It is, make sure its parent is also expanded.
	TreePath        parentPath = path.getParentPath();

	if(parentPath != null)
	    return isExpanded(parentPath);
        return true;
    
public booleanisExpanded(int row)
Returns true if the node at the specified display row is currently expanded.

param
row the row to check, where 0 is the first row in the display
return
true if the node is currently expanded, otherwise false

        TreeUI                  tree = getUI();

        if(tree != null) {
	    TreePath         path = tree.getPathForRow(this, row);

	    if(path != null) {
                Boolean value = (Boolean)expandedState.get(path);

                return (value != null && value.booleanValue());
            }
	}
        return false;
    
public booleanisFixedRowHeight()
Returns true if the height of each display row is a fixed size.

return
true if the height of each row is a fixed size

        return (rowHeight > 0);
    
public booleanisLargeModel()
Returns true if the tree is configured for a large model.

return
true if a large model is suggested
see
#largeModel

        return largeModel;
    
public booleanisPathEditable(javax.swing.tree.TreePath path)
Returns isEditable. This is invoked from the UI before editing begins to insure that the given path can be edited. This is provided as an entry point for subclassers to add filtered editing without having to resort to creating a new editor.

return
true if every parent node and the node itself is editable
see
#isEditable

        return isEditable();
    
public booleanisPathSelected(javax.swing.tree.TreePath path)
Returns true if the item identified by the path is currently selected.

param
path a TreePath identifying a node
return
true if the node is selected

        return getSelectionModel().isPathSelected(path);
    
public booleanisRootVisible()
Returns true if the root node of the tree is displayed.

return
true if the root node of the tree is displayed
see
#rootVisible

        return rootVisible;
    
public booleanisRowSelected(int row)
Returns true if the node identified by row is selected.

param
row an integer specifying a display row, where 0 is the first row in the display
return
true if the node is selected

        return getSelectionModel().isRowSelected(row);
    
public booleanisSelectionEmpty()
Returns true if the selection is currently empty.

return
true if the selection is currently empty

        return getSelectionModel().isSelectionEmpty();
    
public booleanisVisible(javax.swing.tree.TreePath path)
Returns true if the value identified by path is currently viewable, which means it is either the root or all of its parents are expanded. Otherwise, this method returns false.

return
true if the node is viewable, otherwise false

        if(path != null) {
	    TreePath        parentPath = path.getParentPath();

	    if(parentPath != null)
		return isExpanded(parentPath);
	    // Root.
	    return true;
	}
        return false;
    
public voidmakeVisible(javax.swing.tree.TreePath path)
Ensures that the node identified by path is currently viewable.

param
path the TreePath to make visible

        if(path != null) {
	    TreePath        parentPath = path.getParentPath();

	    if(parentPath != null) {
		expandPath(parentPath);
	    }
        }
    
protected java.lang.StringparamString()
Returns a string representation of this JTree. This method is intended to be used only for debugging purposes, and the content and format of the returned string may vary between implementations. The returned string may be empty but may not be null.

return
a string representation of this JTree.

        String rootVisibleString = (rootVisible ?
                                    "true" : "false");
        String showsRootHandlesString = (showsRootHandles ?
					 "true" : "false");
        String editableString = (editable ?
				 "true" : "false");
        String largeModelString = (largeModel ?
				   "true" : "false");
        String invokesStopCellEditingString = (invokesStopCellEditing ?
					       "true" : "false");
        String scrollsOnExpandString = (scrollsOnExpand ?
					"true" : "false");

        return super.paramString() +
        ",editable=" + editableString +
        ",invokesStopCellEditing=" + invokesStopCellEditingString +
        ",largeModel=" + largeModelString +
        ",rootVisible=" + rootVisibleString +
        ",rowHeight=" + rowHeight +
        ",scrollsOnExpand=" + scrollsOnExpandString +
        ",showsRootHandles=" + showsRootHandlesString +
        ",toggleClickCount=" + toggleClickCount +
        ",visibleRowCount=" + visibleRowCount;
    
private voidreadObject(java.io.ObjectInputStream s)

        s.defaultReadObject();

	// Create an instance of expanded state.

	expandedState = new Hashtable();

	expandedStack = new Stack();

        Vector          values = (Vector)s.readObject();
        int             indexCounter = 0;
        int             maxCounter = values.size();

        if(indexCounter < maxCounter && values.elementAt(indexCounter).
           equals("cellRenderer")) {
            cellRenderer = (TreeCellRenderer)values.elementAt(++indexCounter);
            indexCounter++;
        }
        if(indexCounter < maxCounter && values.elementAt(indexCounter).
           equals("cellEditor")) {
            cellEditor = (TreeCellEditor)values.elementAt(++indexCounter);
            indexCounter++;
        }
        if(indexCounter < maxCounter && values.elementAt(indexCounter).
           equals("treeModel")) {
            treeModel = (TreeModel)values.elementAt(++indexCounter);
            indexCounter++;
        }
        if(indexCounter < maxCounter && values.elementAt(indexCounter).
           equals("selectionModel")) {
            selectionModel = (TreeSelectionModel)values.elementAt(++indexCounter);
            indexCounter++;
        }
        if(indexCounter < maxCounter && values.elementAt(indexCounter).
           equals("expandedState")) {
	    unarchiveExpandedState(values.elementAt(++indexCounter));
            indexCounter++;
        }
	// Reinstall the redirector.
        if(listenerList.getListenerCount(TreeSelectionListener.class) != 0) {
            selectionRedirector = new TreeSelectionRedirector();
            selectionModel.addTreeSelectionListener(selectionRedirector);
        }
	// Listener to TreeModel.
	if(treeModel != null) {
	    treeModelListener = createTreeModelListener();
	    if(treeModelListener != null)
		treeModel.addTreeModelListener(treeModelListener);
	}
    
protected booleanremoveDescendantSelectedPaths(javax.swing.tree.TreePath path, boolean includePath)
Removes any paths in the selection that are descendants of path. If includePath is true and path is selected, it will be removed from the selection.

return
true if a descendant was selected
since
1.3

	TreePath[]    toRemove = getDescendantSelectedPaths(path, includePath);

	if (toRemove != null) {
	    getSelectionModel().removeSelectionPaths(toRemove);
	    return true;
	}
	return false;
    
voidremoveDescendantSelectedPaths(javax.swing.event.TreeModelEvent e)
Removes any paths from the selection model that are descendants of the nodes identified by in e.

	TreePath            pPath = e.getTreePath();
	Object[]            oldChildren = e.getChildren();
	TreeSelectionModel  sm = getSelectionModel();

	if (sm != null && pPath != null && oldChildren != null &&
	    oldChildren.length > 0) {
	    for (int counter = oldChildren.length - 1; counter >= 0;
		 counter--) {
		// Might be better to call getDescendantSelectedPaths
		// numerous times, then push to the model.
		removeDescendantSelectedPaths(pPath.pathByAddingChild
					      (oldChildren[counter]), true);
	    }
	}
    
protected voidremoveDescendantToggledPaths(java.util.Enumeration toRemove)
Removes any descendants of the TreePaths in toRemove that have been expanded.

	 if(toRemove != null) {
	     while(toRemove.hasMoreElements()) {
		 Enumeration         descendants = getDescendantToggledPaths
		                         ((TreePath)toRemove.nextElement());

		 if(descendants != null) {
		     while(descendants.hasMoreElements()) {
			 expandedState.remove(descendants.nextElement());
		     }
		 }
	     }
	 }
     
public voidremoveSelectionInterval(int index0, int index1)
Removes the nodes between index0 and index1, inclusive, from the selection.

param
index0 an integer specifying a display row, where 0 is the first row in the display
param
index1 an integer specifying a second display row

        TreePath[]         paths = getPathBetweenRows(index0, index1);

        this.getSelectionModel().removeSelectionPaths(paths);
    
public voidremoveSelectionPath(javax.swing.tree.TreePath path)
Removes the node identified by the specified path from the current selection.

param
path the TreePath identifying a node

        this.getSelectionModel().removeSelectionPath(path);
    
public voidremoveSelectionPaths(javax.swing.tree.TreePath[] paths)
Removes the nodes identified by the specified paths from the current selection.

param
paths an array of TreePath objects that specifies the nodes to remove

        this.getSelectionModel().removeSelectionPaths(paths);
    
public voidremoveSelectionRow(int row)
Removes the row at the index row from the current selection.

param
row the row to remove

        int[]             rows = { row };

        removeSelectionRows(rows);
    
public voidremoveSelectionRows(int[] rows)
Removes the rows that are selected at each of the specified rows.

param
rows an array of ints specifying display rows, where 0 is the first row in the display

        TreeUI             ui = getUI();

        if(ui != null && rows != null) {
            int                  numRows = rows.length;
            TreePath[]           paths = new TreePath[numRows];

            for(int counter = 0; counter < numRows; counter++)
                paths[counter] = ui.getPathForRow(this, rows[counter]);
            removeSelectionPaths(paths);
        }
    
public voidremoveTreeExpansionListener(javax.swing.event.TreeExpansionListener tel)
Removes a listener for TreeExpansion events.

param
tel the TreeExpansionListener to remove

        listenerList.remove(TreeExpansionListener.class, tel);
	if (uiTreeExpansionListener == tel) {
	    uiTreeExpansionListener = null;
	}
    
public voidremoveTreeSelectionListener(javax.swing.event.TreeSelectionListener tsl)
Removes a TreeSelection listener.

param
tsl the TreeSelectionListener to remove

        listenerList.remove(TreeSelectionListener.class,tsl);
        if(listenerList.getListenerCount(TreeSelectionListener.class) == 0
           && selectionRedirector != null) {
            selectionModel.removeTreeSelectionListener
                (selectionRedirector);
            selectionRedirector = null;
        }
    
public voidremoveTreeWillExpandListener(javax.swing.event.TreeWillExpandListener tel)
Removes a listener for TreeWillExpand events.

param
tel the TreeWillExpandListener to remove

        listenerList.remove(TreeWillExpandListener.class, tel);
    
public voidscrollPathToVisible(javax.swing.tree.TreePath path)
Makes sure all the path components in path are expanded (except for the last path component) and scrolls so that the node identified by the path is displayed. Only works when this JTree is contained in a JScrollPane.

param
path the TreePath identifying the node to bring into view

	if(path != null) {
	    makeVisible(path);

	    Rectangle          bounds = getPathBounds(path);

	    if(bounds != null) {
		scrollRectToVisible(bounds);
		if (accessibleContext != null) {
		    ((AccessibleJTree)accessibleContext).fireVisibleDataPropertyChange();
		}
	    }
	}
    
public voidscrollRowToVisible(int row)
Scrolls the item identified by row until it is displayed. The minimum of amount of scrolling necessary to bring the row into view is performed. Only works when this JTree is contained in a JScrollPane.

param
row an integer specifying the row to scroll, where 0 is the first row in the display

	scrollPathToVisible(getPathForRow(row));
    
public voidsetAnchorSelectionPath(javax.swing.tree.TreePath newPath)
Sets the path identified as the anchor. The anchor is not maintained by JTree, rather the UI will update it.

param
newPath the new anchor path
since
1.3
beaninfo
bound: true description: Anchor selection path

	TreePath          oldValue = anchorPath;

	anchorPath = newPath;
	firePropertyChange(ANCHOR_SELECTION_PATH_PROPERTY, oldValue, newPath);
    
public voidsetCellEditor(javax.swing.tree.TreeCellEditor cellEditor)
Sets the cell editor. A null value implies that the tree cannot be edited. If this represents a change in the cellEditor, the propertyChange method is invoked on all listeners.

param
cellEditor the TreeCellEditor to use
beaninfo
bound: true description: The cell editor. A null value implies the tree cannot be edited.

        TreeCellEditor        oldEditor = this.cellEditor;

        this.cellEditor = cellEditor;
        firePropertyChange(CELL_EDITOR_PROPERTY, oldEditor, cellEditor);
        invalidate();
    
public voidsetCellRenderer(javax.swing.tree.TreeCellRenderer x)
Sets the TreeCellRenderer that will be used to draw each cell.

param
x the TreeCellRenderer that is to render each cell
beaninfo
bound: true description: The TreeCellRenderer that will be used to draw each cell.

        TreeCellRenderer oldValue = cellRenderer;

        cellRenderer = x;
        firePropertyChange(CELL_RENDERER_PROPERTY, oldValue, cellRenderer);
        invalidate();
    
public voidsetDragEnabled(boolean b)
Turns on or off automatic drag handling. In order to enable automatic drag handling, this property should be set to {@code true}, and the tree's {@code TransferHandler} needs to be {@code non-null}. The default value of the {@code dragEnabled} property is {@code false}.

The job of honoring this property, and recognizing a user drag gesture, lies with the look and feel implementation, and in particular, the tree's {@code TreeUI}. When automatic drag handling is enabled, most look and feels (including those that subclass {@code BasicLookAndFeel}) begin a drag and drop operation whenever the user presses the mouse button over an item and then moves the mouse a few pixels. Setting this property to {@code true} can therefore have a subtle effect on how selections behave.

If a look and feel is used that ignores this property, you can still begin a drag and drop operation by calling {@code exportAsDrag} on the tree's {@code TransferHandler}.

param
b whether or not to enable automatic drag handling
exception
HeadlessException if b is true and GraphicsEnvironment.isHeadless() returns true
see
java.awt.GraphicsEnvironment#isHeadless
see
#getDragEnabled
see
#setTransferHandler
see
TransferHandler
since
1.4
beaninfo
description: determines whether automatic drag handling is enabled bound: false

        if (b && GraphicsEnvironment.isHeadless()) {
            throw new HeadlessException();
        }
	dragEnabled = b;
    
java.lang.ObjectsetDropLocation(javax.swing.TransferHandler$DropLocation location, java.lang.Object state, boolean forDrop)
Called to set or clear the drop location during a DnD operation. In some cases, the component may need to use it's internal selection temporarily to indicate the drop location. To help facilitate this, this method returns and accepts as a parameter a state object. This state object can be used to store, and later restore, the selection state. Whatever this method returns will be passed back to it in future calls, as the state parameter. If it wants the DnD system to continue storing the same state, it must pass it back every time. Here's how this is used:

Let's say that on the first call to this method the component decides to save some state (because it is about to use the selection to show a drop index). It can return a state object to the caller encapsulating any saved selection state. On a second call, let's say the drop location is being changed to something else. The component doesn't need to restore anything yet, so it simply passes back the same state object to have the DnD system continue storing it. Finally, let's say this method is messaged with null. This means DnD is finished with this component for now, meaning it should restore state. At this point, it can use the state parameter to restore said state, and of course return null since there's no longer anything to store.

param
location the drop location (as calculated by dropLocationForPoint) or null if there's no longer a valid drop location
param
state the state object saved earlier for this component, or null
param
forDrop whether or not the method is being called because an actual drop occurred
return
any saved state for this component, or null if none


        Object retVal = null;
        DropLocation treeLocation = (DropLocation)location;

        if (dropMode == DropMode.USE_SELECTION) {
            if (treeLocation == null) {
                if (!forDrop && state != null) {
                    setSelectionPaths(((TreePath[][])state)[0]);
                    setAnchorSelectionPath(((TreePath[][])state)[1][0]);
                    setLeadSelectionPath(((TreePath[][])state)[1][1]);
                }
            } else {
                if (dropLocation == null) {
                    TreePath[] paths = getSelectionPaths();
                    if (paths == null) {
                        paths = new TreePath[0];
                    }

                    retVal = new TreePath[][] {paths,
                            {getAnchorSelectionPath(), getLeadSelectionPath()}};
                } else {
                    retVal = state;
                }

                setSelectionPath(treeLocation.getPath());
            }
        }

        DropLocation old = dropLocation;
        dropLocation = treeLocation;
        firePropertyChange("dropLocation", old, dropLocation);

        return retVal;
    
public final voidsetDropMode(javax.swing.DropMode dropMode)
Sets the drop mode for this component. For backward compatibility, the default for this property is DropMode.USE_SELECTION. Usage of one of the other modes is recommended, however, for an improved user experience. DropMode.ON, for instance, offers similar behavior of showing items as selected, but does so without affecting the actual selection in the tree.

JTree supports the following drop modes:

  • DropMode.USE_SELECTION
  • DropMode.ON
  • DropMode.INSERT
  • DropMode.ON_OR_INSERT

The drop mode is only meaningful if this component has a TransferHandler that accepts drops.

param
dropMode the drop mode to use
throws
IllegalArgumentException if the drop mode is unsupported or null
see
#getDropMode
see
#getDropLocation
see
#setTransferHandler
see
TransferHandler
since
1.6

        if (dropMode != null) {
            switch (dropMode) {
                case USE_SELECTION:
                case ON:
                case INSERT:
                case ON_OR_INSERT:
                    this.dropMode = dropMode;
                    return;
            }
        }

        throw new IllegalArgumentException(dropMode + ": Unsupported drop mode for tree");
    
public voidsetEditable(boolean flag)
Determines whether the tree is editable. Fires a property change event if the new setting is different from the existing setting.

param
flag a boolean value, true if the tree is editable
beaninfo
bound: true description: Whether the tree is editable.

        boolean                 oldValue = this.editable;

        this.editable = flag;
        firePropertyChange(EDITABLE_PROPERTY, oldValue, flag);
        if (accessibleContext != null) {
            accessibleContext.firePropertyChange(
                AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 
                (oldValue ? AccessibleState.EDITABLE : null),
                (flag ? AccessibleState.EDITABLE : null));
        }
    
protected voidsetExpandedState(javax.swing.tree.TreePath path, boolean state)
Sets the expanded state of this JTree. If state is true, all parents of path and path are marked as expanded. If state is false, all parents of path are marked EXPANDED, but path itself is marked collapsed.

This will fail if a TreeWillExpandListener vetos it.

	if(path != null) {
	    // Make sure all parents of path are expanded.
	    Stack         stack;
	    TreePath      parentPath = path.getParentPath();

	    if (expandedStack.size() == 0) {
		stack = new Stack();
	    }
	    else {
		stack = (Stack)expandedStack.pop();
	    }

	    try {
		while(parentPath != null) {
		    if(isExpanded(parentPath)) {
			parentPath = null;
		    }
		    else {
			stack.push(parentPath);
			parentPath = parentPath.getParentPath();
		    }
		}
		for(int counter = stack.size() - 1; counter >= 0; counter--) {
		    parentPath = (TreePath)stack.pop();
		    if(!isExpanded(parentPath)) {
			try {
			    fireTreeWillExpand(parentPath);
			} catch (ExpandVetoException eve) {
			    // Expand vetoed!
			    return;
			}
			expandedState.put(parentPath, Boolean.TRUE);
			fireTreeExpanded(parentPath);
			if (accessibleContext != null) {
			    ((AccessibleJTree)accessibleContext).
			                      fireVisibleDataPropertyChange();
			}
		    }
		}
	    }
	    finally {
		if (expandedStack.size() < TEMP_STACK_SIZE) {
		    stack.removeAllElements();
		    expandedStack.push(stack);
		}
	    }
	    if(!state) {
		// collapse last path.
		Object          cValue = expandedState.get(path);

		if(cValue != null && ((Boolean)cValue).booleanValue()) {
		    try {
			fireTreeWillCollapse(path);
		    }
		    catch (ExpandVetoException eve) {
			return;
		    }
		    expandedState.put(path, Boolean.FALSE);
		    fireTreeCollapsed(path);
		    if (removeDescendantSelectedPaths(path, false) &&
			!isPathSelected(path)) {
			// A descendant was selected, select the parent.
			addSelectionPath(path);
		    }
		    if (accessibleContext != null) {
			((AccessibleJTree)accessibleContext).
			            fireVisibleDataPropertyChange();
		    }
		}
	    }
	    else {
		// Expand last path.
		Object          cValue = expandedState.get(path);

		if(cValue == null || !((Boolean)cValue).booleanValue()) {
		    try {
			fireTreeWillExpand(path);
		    }
		    catch (ExpandVetoException eve) {
			return;
		    }
		    expandedState.put(path, Boolean.TRUE);
		    fireTreeExpanded(path);
		    if (accessibleContext != null) {
			((AccessibleJTree)accessibleContext).
			                  fireVisibleDataPropertyChange();
		    }
		}
	    }
	}
    
public voidsetExpandsSelectedPaths(boolean newValue)
Configures the expandsSelectedPaths property. If true, any time the selection is changed, either via the TreeSelectionModel, or the cover methods provided by JTree, the TreePaths parents will be expanded to make them visible (visible meaning the parent path is expanded, not necessarily in the visible rectangle of the JTree). If false, when the selection changes the nodes parent is not made visible (all its parents expanded). This is useful if you wish to have your selection model maintain paths that are not always visible (all parents expanded).

param
newValue the new value for expandsSelectedPaths
since
1.3
beaninfo
bound: true description: Indicates whether changes to the selection should make the parent of the path visible.

	boolean         oldValue = expandsSelectedPaths;

	expandsSelectedPaths = newValue;
	firePropertyChange(EXPANDS_SELECTED_PATHS_PROPERTY, oldValue,
			   newValue);
    
public voidsetInvokesStopCellEditing(boolean newValue)
Determines what happens when editing is interrupted by selecting another node in the tree, a change in the tree's data, or by some other means. Setting this property to true causes the changes to be automatically saved when editing is interrupted.

Fires a property change for the INVOKES_STOP_CELL_EDITING_PROPERTY.

param
newValue true means that stopCellEditing is invoked when editing is interrupted, and data is saved; false means that cancelCellEditing is invoked, and changes are lost
beaninfo
bound: true description: Determines what happens when editing is interrupted, selecting another node in the tree, a change in the tree's data, or some other means.

        boolean                  oldValue = invokesStopCellEditing;

        invokesStopCellEditing = newValue;
        firePropertyChange(INVOKES_STOP_CELL_EDITING_PROPERTY, oldValue,
                           newValue);
    
public voidsetLargeModel(boolean newValue)
Specifies whether the UI should use a large model. (Not all UIs will implement this.) Fires a property change for the LARGE_MODEL_PROPERTY.

param
newValue true to suggest a large model to the UI
see
#largeModel
beaninfo
bound: true description: Whether the UI should use a large model.

        boolean                oldValue = largeModel;

        largeModel = newValue;
        firePropertyChange(LARGE_MODEL_PROPERTY, oldValue, newValue);
    
public voidsetLeadSelectionPath(javax.swing.tree.TreePath newPath)
Sets the path identifies as the lead. The lead may not be selected. The lead is not maintained by JTree, rather the UI will update it.

param
newPath the new lead path
since
1.3
beaninfo
bound: true description: Lead selection path

	TreePath          oldValue = leadPath;

	leadPath = newPath;
	firePropertyChange(LEAD_SELECTION_PATH_PROPERTY, oldValue, newPath);
    
public voidsetModel(javax.swing.tree.TreeModel newModel)
Sets the TreeModel that will provide the data.

param
newModel the TreeModel that is to provide the data
beaninfo
bound: true description: The TreeModel that will provide the data.

        clearSelection();

        TreeModel oldModel = treeModel;

	if(treeModel != null && treeModelListener != null)
	    treeModel.removeTreeModelListener(treeModelListener);

        if (accessibleContext != null) {
	    if (treeModel != null) {
                treeModel.removeTreeModelListener((TreeModelListener)accessibleContext);
	    }
            if (newModel != null) {
	        newModel.addTreeModelListener((TreeModelListener)accessibleContext);
	    }
        }

        treeModel = newModel;
	clearToggledPaths();
	if(treeModel != null) {
	    if(treeModelListener == null)
		treeModelListener = createTreeModelListener();
	    if(treeModelListener != null)
		treeModel.addTreeModelListener(treeModelListener);
	    // Mark the root as expanded, if it isn't a leaf.
	    if(treeModel.getRoot() != null &&
               !treeModel.isLeaf(treeModel.getRoot())) {
		expandedState.put(new TreePath(treeModel.getRoot()),
				  Boolean.TRUE);
            }
	}
        firePropertyChange(TREE_MODEL_PROPERTY, oldModel, treeModel);
        invalidate();
    
public voidsetRootVisible(boolean rootVisible)
Determines whether or not the root node from the TreeModel is visible.

param
rootVisible true if the root node of the tree is to be displayed
see
#rootVisible
beaninfo
bound: true description: Whether or not the root node from the TreeModel is visible.

        boolean                oldValue = this.rootVisible;

        this.rootVisible = rootVisible;
        firePropertyChange(ROOT_VISIBLE_PROPERTY, oldValue, this.rootVisible);
        if (accessibleContext != null) {
            ((AccessibleJTree)accessibleContext).fireVisibleDataPropertyChange();
        }
    
public voidsetRowHeight(int rowHeight)
Sets the height of each cell, in pixels. If the specified value is less than or equal to zero the current cell renderer is queried for each row's height.

param
rowHeight the height of each cell, in pixels
beaninfo
bound: true description: The height of each cell.

        int                oldValue = this.rowHeight;

        this.rowHeight = rowHeight;
	rowHeightSet = true;
        firePropertyChange(ROW_HEIGHT_PROPERTY, oldValue, this.rowHeight);
        invalidate();
    
public voidsetScrollsOnExpand(boolean newValue)
Sets the scrollsOnExpand property, which determines whether the tree might scroll to show previously hidden children. If this property is true (the default), when a node expands the tree can use scrolling to make the maximum possible number of the node's descendants visible. In some look and feels, trees might not need to scroll when expanded; those look and feels will ignore this property.

param
newValue false to disable scrolling on expansion; true to enable it
see
#getScrollsOnExpand
beaninfo
bound: true description: Indicates if a node descendant should be scrolled when expanded.

	boolean           oldValue = scrollsOnExpand;

	scrollsOnExpand = newValue;
	scrollsOnExpandSet = true;
        firePropertyChange(SCROLLS_ON_EXPAND_PROPERTY, oldValue,
                           newValue);
    
public voidsetSelectionInterval(int index0, int index1)
Selects the nodes between index0 and index1, inclusive.

param
index0 an integer specifying a display row, where 0 is the first row in the display
param
index1 an integer specifying a second display row

        TreePath[]         paths = getPathBetweenRows(index0, index1);

        this.getSelectionModel().setSelectionPaths(paths);
    
public voidsetSelectionModel(javax.swing.tree.TreeSelectionModel selectionModel)
Sets the tree's selection model. When a null value is specified an empty selectionModel is used, which does not allow selections.

param
selectionModel the TreeSelectionModel to use, or null to disable selections
see
TreeSelectionModel
beaninfo
bound: true description: The tree's selection model.

        if(selectionModel == null)
            selectionModel = EmptySelectionModel.sharedInstance();

        TreeSelectionModel         oldValue = this.selectionModel;

	if (this.selectionModel != null && selectionRedirector != null) {
            this.selectionModel.removeTreeSelectionListener
		                (selectionRedirector);
	}
        if (accessibleContext != null) {
           this.selectionModel.removeTreeSelectionListener((TreeSelectionListener)accessibleContext);
           selectionModel.addTreeSelectionListener((TreeSelectionListener)accessibleContext);
        }

        this.selectionModel = selectionModel;
	if (selectionRedirector != null) {
            this.selectionModel.addTreeSelectionListener(selectionRedirector);
	}
        firePropertyChange(SELECTION_MODEL_PROPERTY, oldValue,
                           this.selectionModel);

        if (accessibleContext != null) {
            accessibleContext.firePropertyChange(
                    AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY,
                    Boolean.valueOf(false), Boolean.valueOf(true));
        }
    
public voidsetSelectionPath(javax.swing.tree.TreePath path)
Selects the node identified by the specified path. If any component of the path is hidden (under a collapsed node), and getExpandsSelectedPaths is true it is exposed (made viewable).

param
path the TreePath specifying the node to select

        getSelectionModel().setSelectionPath(path);
    
public voidsetSelectionPaths(javax.swing.tree.TreePath[] paths)
Selects the nodes identified by the specified array of paths. If any component in any of the paths is hidden (under a collapsed node), and getExpandsSelectedPaths is true it is exposed (made viewable).

param
paths an array of TreePath objects that specifies the nodes to select

        getSelectionModel().setSelectionPaths(paths);
    
public voidsetSelectionRow(int row)
Selects the node at the specified row in the display.

param
row the row to select, where 0 is the first row in the display

        int[]             rows = { row };

        setSelectionRows(rows);
    
public voidsetSelectionRows(int[] rows)
Selects the nodes corresponding to each of the specified rows in the display. If a particular element of rows is < 0 or >= getRowCount, it will be ignored. If none of the elements in rows are valid rows, the selection will be cleared. That is it will be as if clearSelection was invoked.

param
rows an array of ints specifying the rows to select, where 0 indicates the first row in the display

        TreeUI               ui = getUI();

        if(ui != null && rows != null) {
            int                  numRows = rows.length;
            TreePath[]           paths = new TreePath[numRows];

            for(int counter = 0; counter < numRows; counter++) {
                paths[counter] = ui.getPathForRow(this, rows[counter]);
	    }
            setSelectionPaths(paths);
        }
    
public voidsetShowsRootHandles(boolean newValue)
Sets the value of the showsRootHandles property, which specifies whether the node handles should be displayed. The default value of this property depends on the constructor used to create the JTree. Some look and feels might not support handles; they will ignore this property.

param
newValue true if root handles should be displayed; otherwise, false
see
#showsRootHandles
see
#getShowsRootHandles
beaninfo
bound: true description: Whether the node handles are to be displayed.

        boolean                oldValue = showsRootHandles;
	TreeModel              model = getModel();

        showsRootHandles = newValue;
        showsRootHandlesSet = true;
        firePropertyChange(SHOWS_ROOT_HANDLES_PROPERTY, oldValue,
                           showsRootHandles);
        if (accessibleContext != null) {
            ((AccessibleJTree)accessibleContext).fireVisibleDataPropertyChange();
        }
        invalidate();
    
public voidsetToggleClickCount(int clickCount)
Sets the number of mouse clicks before a node will expand or close. The default is two.

since
1.3
beaninfo
bound: true description: Number of clicks before a node will expand/collapse.

	int         oldCount = toggleClickCount;

	toggleClickCount = clickCount;
	firePropertyChange(TOGGLE_CLICK_COUNT_PROPERTY, oldCount,
			   clickCount);
    
public voidsetUI(javax.swing.plaf.TreeUI ui)
Sets the L&F object that renders this component.

param
ui the TreeUI L&F object
see
UIDefaults#getUI
beaninfo
bound: true hidden: true attribute: visualUpdate true description: The UI object that implements the Component's LookAndFeel.

        if ((TreeUI)this.ui != ui) {
	    settingUI = true;
	    uiTreeExpansionListener = null;
	    try {
		super.setUI(ui);
	    }
	    finally {
		settingUI = false;
	    }
        }
    
voidsetUIProperty(java.lang.String propertyName, java.lang.Object value)

        if (propertyName == "rowHeight") {
	    if (!rowHeightSet) {
		setRowHeight(((Number)value).intValue());
		rowHeightSet = false;
	    }
	} else if (propertyName == "scrollsOnExpand") {
	    if (!scrollsOnExpandSet) {
		setScrollsOnExpand(((Boolean)value).booleanValue());
		scrollsOnExpandSet = false;
	    }
	} else if (propertyName == "showsRootHandles") {
            if (!showsRootHandlesSet) {
                setShowsRootHandles(((Boolean)value).booleanValue());
                showsRootHandlesSet = false;
            }
        } else {
	    super.setUIProperty(propertyName, value);
	}
    
public voidsetVisibleRowCount(int newCount)
Sets the number of rows that are to be displayed. This will only work if the tree is contained in a JScrollPane, and will adjust the preferred size and size of that scrollpane.

param
newCount the number of rows to display
beaninfo
bound: true description: The number of rows that are to be displayed.

        int                 oldCount = visibleRowCount;

        visibleRowCount = newCount;
        firePropertyChange(VISIBLE_ROW_COUNT_PROPERTY, oldCount,
                           visibleRowCount);
        invalidate();
        if (accessibleContext != null) {
            ((AccessibleJTree)accessibleContext).fireVisibleDataPropertyChange();
        }
    
private voidstartDropTimer()

        if (dropTimer == null) {
            dropTimer = new TreeTimer();
        }
        dropTimer.start();
    
public voidstartEditingAtPath(javax.swing.tree.TreePath path)
Selects the node identified by the specified path and initiates editing. The edit-attempt fails if the CellEditor does not allow editing for the specified item.

param
path the TreePath identifying a node

        TreeUI                  tree = getUI();

        if(tree != null)
            tree.startEditingAtPath(this, path);
    
public booleanstopEditing()
Ends the current editing session. (The DefaultTreeCellEditor object saves any edits that are currently in progress on a cell. Other implementations may operate differently.) Has no effect if the tree isn't being edited.
Note:
To make edit-saves automatic whenever the user changes their position in the tree, use {@link #setInvokesStopCellEditing}.

return
true if editing was in progress and is now stopped, false if editing was not in progress

        TreeUI                  tree = getUI();

        if(tree != null)
            return tree.stopEditing(this);
        return false;
    
public voidtreeDidChange()
Sent when the tree has changed enough that we need to resize the bounds, but not enough that we need to remove the expanded node set (e.g nodes were expanded or collapsed, or nodes were inserted into the tree). You should never have to invoke this, the UI will invoke this as it needs to.

        revalidate();
        repaint();
    
private voidunarchiveExpandedState(java.lang.Object state)
Updates the expanded state of nodes in the tree based on the previously archived state state.

	if(state instanceof Vector) {
	    Vector          paths = (Vector)state;

	    for(int counter = paths.size() - 1; counter >= 0; counter--) {
		Boolean        eState = (Boolean)paths.elementAt(counter--);
		TreePath       path;

		try {
		    path = getPathForIndexs((int[])paths.elementAt(counter));
		    if(path != null)
			expandedState.put(path, eState);
		} catch (Error error) {}
	    }
	}
    
public voidupdateUI()
Notification from the UIManager that the L&F has changed. Replaces the current UI object with the latest version from the UIManager.

see
JComponent#updateUI

        setUI((TreeUI)UIManager.getUI(this));

        TreeCellRenderer renderer = getCellRenderer();
        if (renderer instanceof Component) {
            SwingUtilities.updateComponentTreeUI((Component)renderer);
        }

        TreeCellEditor editor = getCellEditor();
        if (editor instanceof Component) {
            SwingUtilities.updateComponentTreeUI((Component)editor);
        } else if (editor instanceof DefaultCellEditor) {
            Component comp = ((DefaultCellEditor)editor).getComponent();
            if (comp != null) {
                SwingUtilities.updateComponentTreeUI(comp);
            }
        }
    
private voidwriteObject(java.io.ObjectOutputStream s)

        Vector      values = new Vector();

        s.defaultWriteObject();
        // Save the cellRenderer, if its Serializable.
        if(cellRenderer != null && cellRenderer instanceof Serializable) {
            values.addElement("cellRenderer");
            values.addElement(cellRenderer);
        }
        // Save the cellEditor, if its Serializable.
        if(cellEditor != null && cellEditor instanceof Serializable) {
            values.addElement("cellEditor");
            values.addElement(cellEditor);
        }
        // Save the treeModel, if its Serializable.
        if(treeModel != null && treeModel instanceof Serializable) {
            values.addElement("treeModel");
            values.addElement(treeModel);
        }
        // Save the selectionModel, if its Serializable.
        if(selectionModel != null && selectionModel instanceof Serializable) {
            values.addElement("selectionModel");
            values.addElement(selectionModel);
        }

	Object      expandedData = getArchivableExpandedState();

	if(expandedData != null) {
            values.addElement("expandedState");
            values.addElement(expandedData);
	}

        s.writeObject(values);
        if (getUIClassID().equals(uiClassID)) {
            byte count = JComponent.getWriteObjCounter(this);
            JComponent.setWriteObjCounter(this, --count);
            if (count == 0 && ui != null) {
                ui.installUI(this);
            }
        }