Top Description Inners Fields Constructors Methods
javafx.scene.control

public Class TreeView<T>

extends Control
Class Inheritance
Annotations
@DefaultProperty:root
Type Parameters
<T>
The type of the item contained within the TreeItem value property for all tree items in this TreeView.
Imports
javafx.css.converter.SizeConverter, com.sun.javafx.scene.control.Properties, com.sun.javafx.scene.control.behavior.TreeCellBehavior, javafx.scene.control.skin.TreeViewSkin, javafx.application.Platform, javafx.beans.DefaultProperty, .InvalidationListener, .WeakInvalidationListener, javafx.beans.property.BooleanProperty, .DoubleProperty, .ObjectProperty, .ObjectPropertyBase, .ReadOnlyIntegerProperty, .ReadOnlyIntegerWrapper, .ReadOnlyObjectProperty, .ReadOnlyObjectWrapper, .SimpleBooleanProperty, .SimpleObjectProperty, javafx.beans.value.ChangeListener, .WeakChangeListener, javafx.collections.ListChangeListener, javafx.css.CssMetaData, .Styleable, .StyleableDoubleProperty, .StyleableProperty, javafx.event.Event, .EventHandler, .EventType, .WeakEventHandler, javafx.scene.AccessibleAttribute, .AccessibleRole, javafx.scene.control.TreeItem.TreeModificationEvent, javafx.scene.layout.Region, javafx.util.Callback, java.lang.ref.SoftReference, .WeakReference, java.util.ArrayList, .Collections, .Comparator, .HashMap, .List, .Map

The TreeView control provides a view on to a tree root (of type TreeItem). By using a TreeView, it is possible to drill down into the children of a TreeItem, recursively until a TreeItem has no children (that is, it is a leaf node in the tree). To facilitate this, unlike controls like ListView, in TreeView it is necessary to only specify the root node.

For more information on building up a tree using this approach, refer to the TreeItem class documentation. Briefly however, to create a TreeView, you should do something along the lines of the following:

 TreeItem<String> root = new TreeItem<>("Root Node");
root.setExpanded(true);
root.getChildren().addAll(
    new TreeItem<>("Item 1"),
    new TreeItem<>("Item 2"),
    new TreeItem<>("Item 3")
);
TreeView<String> treeView = new TreeView<>(root);
Image of the TreeView control

A TreeView may be configured to optionally hide the root node by setting the showRoot property to false. If the root node is hidden, there is one less level of indentation, and all children nodes of the root node are shown. By default, the root node is shown in the TreeView.

TreeView Selection / Focus APIs

To track selection and focus, it is necessary to become familiar with the SelectionModel and FocusModel classes. A TreeView has at most one instance of each of these classes, available from selectionModel and focusModel properties respectively. Whilst it is possible to use this API to set a new selection model, in most circumstances this is not necessary - the default selection and focus models should work in most circumstances.

The default SelectionModel used when instantiating a TreeView is an implementation of the MultipleSelectionModel abstract class. However, as noted in the API documentation for the selectionMode property, the default value is SelectionMode#SINGLE. To enable multiple selection in a default TreeView instance, it is therefore necessary to do the following:

 treeView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

Customizing TreeView Visuals

The visuals of the TreeView can be entirely customized by replacing the default cell factory. A cell factory is used to generate TreeCell instances, which are used to represent an item in the TreeView. See the Cell class documentation for a more complete description of how to write custom Cells.

Warning: Nodes should not be inserted directly into the TreeView cells

TreeView allows for it's cells to contain elements of any type, including Node instances. Putting nodes into the TreeView cells is strongly discouraged, as it can lead to unexpected results.

Important points to note:

The following minimal example shows how to create a custom cell factory for TreeView containing Nodes:

 TreeItem<Color> treeRoot = new TreeItem<>();
 treeRoot.setExpanded(true);
 TreeView<Color> treeView = new TreeView<>(treeRoot);

 treeRoot.getChildren().addAll(
     new TreeItem<>(Color.RED),
     new TreeItem<>(Color.GREEN),
     new TreeItem<>(Color.BLUE));

 treeView.setCellFactory(p -> {
     return new TreeCell<Color>() {
     private final Rectangle rectangle;
     {
         setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
         rectangle = new Rectangle(10, 10);
     }

     @Override
     protected void updateItem(Color item, boolean empty) {
         super.updateItem(item, empty);

         if (item == null || empty) {
             setGraphic(null);
         } else {
             rectangle.setFill(item);
             setGraphic(rectangle);
         }
     }
 };});

This example has an anonymous custom TreeCell class in the custom cell factory. Note that the Rectangle (Node) object needs to be created in the instance initialization block or the constructor of the custom TreeCell class and updated/used in its updateItem method.

Editing

This control supports inline editing of values, and this section attempts to give an overview of the available APIs and how you should use them.

Firstly, cell editing most commonly requires a different user interface than when a cell is not being edited. This is the responsibility of the Cell implementation being used. For TreeView, this is the responsibility of the cell factory. It is your choice whether the cell is permanently in an editing state (e.g. this is common for CheckBox cells), or to switch to a different UI when editing begins (e.g. when a double-click is received on a cell).

To know when editing has been requested on a cell, simply override the javafx.scene.control.Cell#startEdit() method, and update the cell text and graphic properties as appropriate (e.g. set the text to null and set the graphic to be a TextField). Additionally, you should also override Cell#cancelEdit() to reset the UI back to its original visual state when the editing concludes. In both cases it is important that you also ensure that you call the super method to have the cell perform all duties it must do to enter or exit its editing mode.

Once your cell is in an editing state, the next thing you are most probably interested in is how to commit or cancel the editing that is taking place. This is your responsibility as the cell factory provider. Your cell implementation will know when the editing is over, based on the user input (e.g. when the user presses the Enter or ESC keys on their keyboard). When this happens, it is your responsibility to call Cell#commitEdit(Object) or Cell#cancelEdit(), as appropriate.

When you call Cell#commitEdit(Object) an event is fired to the TreeView, which you can observe by adding an EventHandler via TreeView#setOnEditCommit(javafx.event.EventHandler). Similarly, you can also observe edit events for edit start and edit cancel.

By default the TreeView edit commit handler is non-null, with a default handler that attempts to overwrite the property value for the item in the currently-being-edited row. It is able to do this as the Cell#commitEdit(Object) method is passed in the new value, and this is passed along to the edit commit handler via the EditEvent that is fired. It is simply a matter of calling EditEvent#getNewValue() to retrieve this value.

It is very important to note that if you call TreeView#setOnEditCommit(javafx.event.EventHandler) with your own EventHandler, then you will be removing the default handler. Unless you then handle the writeback to the property (or the relevant data source), nothing will happen. You can work around this by using the TreeView#addEventHandler(javafx.event.EventType, javafx.event.EventHandler) method to add a TreeView#editCommitEvent() EventType with your desired EventHandler as the second argument. Using this method, you will not replace the default implementation, but you will be notified when an edit commit has occurred.

Hopefully this summary answers some of the commonly asked questions. Fortunately, JavaFX ships with a number of pre-built cell factories that handle all the editing requirements on your behalf. You can find these pre-built cell factories in the javafx.scene.control.cell package.

Since
JavaFX 2.0
See Also
TreeItem, TreeCell

Nested and Inner Type Summary

Modifier and TypeClass and Description
public static class
TreeView.EditEvent<
The type of the input, which is the same type as the TreeView itself.
T
>

An Event subclass used specifically in TreeView for representing edit-related events.

private static class
pack-priv static class
pack-priv static class

Field Summary

Modifier and TypeField and Description
private ObjectProperty<Callback<TreeView<T>, TreeCell<T>>>
private EventHandler<TreeView.EditEvent<T>>
private static final String
private static final EventType<?>
private static final EventType<?>
private static final EventType<?>
private static final EventType<?>
private BooleanProperty
private ReadOnlyObjectWrapper<TreeItem<T>>
private ReadOnlyIntegerWrapper
expandedItemCount

Represents the number of tree nodes presently able to be visible in the TreeView.

private boolean
private DoubleProperty
private ObjectProperty<FocusModel<TreeItem<T>>>
private ObjectProperty<EventHandler<TreeView.EditEvent<T>>>
private ObjectProperty<EventHandler<TreeView.EditEvent<T>>>
private ObjectProperty<EventHandler<TreeView.EditEvent<T>>>
private ObjectProperty<EventHandler<ScrollToEvent<Integer>>>
onScrollTo

Called when there's a request to scroll an index into view using scrollTo(int)

private ObjectProperty<TreeItem<T>>
private final EventHandler<TreeItem.TreeModificationEvent<T>>
private ObjectProperty<MultipleSelectionModel<TreeItem<T>>>
private BooleanProperty
private Map<Integer, SoftReference<TreeItem<T>>>
private WeakEventHandler<TreeItem.TreeModificationEvent<T>>

Constructor Summary

AccessConstructor and Description
public
TreeView()

Creates an empty TreeView.

public
TreeView(TreeItem<T>
The node to be the root in this TreeView.
root
)

Creates a TreeView with the provided root node.

Method Summary

Modifier and TypeMethod and Description
public final ObjectProperty<Callback<TreeView<T>, TreeCell<T>>>

Returns:

the cell factory property
cellFactoryProperty
()

Represents the cell factory that will be used for creating TreeCells, which are used to represent items in the TreeView.

protected Skin<?>
createDefaultSkin()

Overrides javafx.scene.control.Control.createDefaultSkin.

Create a new instance of the default skin for this control.

public void
edit(TreeItem<T>
The TreeItem in the TreeView that should be edited.
item
)

Instructs the TreeView to begin editing the given TreeItem, if the TreeView is editable.

public final BooleanProperty

Returns:

the editable property
editableProperty
()

Specifies whether this TreeView is editable - only if the TreeView and the TreeCells within it are both editable will a TreeCell be able to go into their editing state.

public static <
the type of the TreeItem instances used in this TreeView
T
>
EventType<TreeView.EditEvent<T>>

Returns:

An EventType that indicates some edit event has occurred.
editAnyEvent
()

An EventType that indicates some edit event has occurred.

public static <
the type of the TreeItem instances used in this TreeView
T
>
EventType<TreeView.EditEvent<T>>

Returns:

An EventType used to indicate that an edit event has just been canceled.
editCancelEvent
()

An EventType used to indicate that an edit event has just been canceled within the TreeView upon which the event was fired.

public static <
the type of the TreeItem instances used in this TreeView
T
>
EventType<TreeView.EditEvent<T>>

Returns:

An EventType that is used to indicate that an edit in a TreeView has been committed.
editCommitEvent
()

An EventType that is used to indicate that an edit in a TreeView has been committed.

public final ReadOnlyObjectProperty<TreeItem<T>>

Returns:

the editing item property
editingItemProperty
()

A property used to represent the TreeItem currently being edited in the TreeView, if editing is taking place, or null if no item is being edited.

private ReadOnlyObjectWrapper<TreeItem<T>>
public static <
the type of the TreeItem instances used in this TreeView
T
>
EventType<TreeView.EditEvent<T>>

Returns:

An EventType used to indicate that an edit event has started.
editStartEvent
()

An EventType used to indicate that an edit event has started within the TreeView upon which the event was fired.

public final ReadOnlyIntegerProperty
public final DoubleProperty

Returns:

the fixed cell size property
fixedCellSizeProperty
()

Specifies whether this control has cells that are a fixed height (of the specified value).

public final ObjectProperty<FocusModel<TreeItem<T>>>

Returns:

the focus model property
focusModelProperty
()

The FocusModel provides the API through which it is possible to control focus on zero or one rows of the TreeView.

public final Callback<TreeView<T>, TreeCell<T>>

Returns:

the cell factory
getCellFactory
()

Returns the cell factory that will be used for creating TreeCells, which are used to represent items in the TreeView, or null if no custom cell factory has been set.

public static List<CssMetaData<? extends Styleable, ?>>

Returns:

the CssMetaData
getClassCssMetaData
()

Hides javafx.scene.control.Control.getClassCssMetaData.

Gets the CssMetaData associated with this class, which may include the CssMetaData of its superclasses.

public List<CssMetaData<? extends Styleable, ?>>
getControlCssMetaData()

Overrides javafx.scene.control.Control.getControlCssMetaData.

Gets the unmodifiable list of the control's CSS-styleable properties.

public final TreeItem<T>

Returns:

the TreeItem that is currently being edited in the TreeView
getEditingItem
()

Returns the TreeItem that is currently being edited in the TreeView, or null if no item is being edited.

public final int
public final double

Returns:

A double representing the fixed cell size of this control, or a value less than or equal to zero if fixed cell size mode is disabled.
getFixedCellSize
()

Returns the fixed cell size value.

public final FocusModel<TreeItem<T>>

Returns:

the currently installed FocusModel
getFocusModel
()

Returns the currently installed FocusModel.

public static int

Returns:

An integer representing the number of parents above the given node, or -1 if the given TreeItem is null.
getNodeLevel
(TreeItem<?>
The TreeItem for which the level is needed.
node
)
Deprecated since 8u20. This method does not correctly calculate the distance from the given TreeItem to the root of the TreeView.

Returns the number of levels of 'indentation' of the given TreeItem, based on how many times javafx.scene.control.TreeItem#getParent() can be recursively called.

public final EventHandler<TreeView.EditEvent<T>>

Returns:

the EventHandler that will be called when the user cancels an edit
getOnEditCancel
()

Returns the EventHandler that will be called when the user cancels an edit.

public final EventHandler<TreeView.EditEvent<T>>

Returns:

the EventHandler that will be called when the user commits an edit
getOnEditCommit
()

Returns the EventHandler that will be called when the user commits an edit.

public final EventHandler<TreeView.EditEvent<T>>

Returns:

the EventHandler when the user begins an edit
getOnEditStart
()

Returns the EventHandler that will be called when the user begins an edit.

public EventHandler<ScrollToEvent<Integer>>
public final TreeItem<T>

Returns:

The current root node, or null if no root node exists.
getRoot
()

Returns the current root node of this TreeView, or null if no root node is specified.

public int

Returns:

An integer representing the location in the current TreeView of the first instance of the given TreeItem, or -1 if it is null or can not be found (for example, if a parent (all the way up to the root) is collapsed).
getRow
(TreeItem<T>
The TreeItem for which the index is sought.
item
)

Returns the index position of the given TreeItem, assuming that it is currently accessible through the tree hierarchy (most notably, that all parent tree items are expanded).

public final MultipleSelectionModel<TreeItem<T>>

Returns:

the currently installed selection model
getSelectionModel
()

Returns the currently installed selection model.

public TreeItem<T>

Returns:

The TreeItem in the given index, or null if it is out of bounds.
getTreeItem
(int
The index of the TreeItem being sought.
row
)

Returns the TreeItem in the given index, or null if it is out of bounds.

public int

Returns:

An integer representing the number of parents above the given node, or -1 if the given TreeItem is null.
getTreeItemLevel
(TreeItem<?>
The TreeItem for which the level is needed.
node
)

Returns the number of levels of 'indentation' of the given TreeItem, based on how many times getParent() can be recursively called.

public final boolean
public final boolean

Returns:

true if the root of the TreeView should be shown
isShowRoot
()

Returns true if the root of the TreeView should be shown, and false if it should not.

protected void
layoutChildren()

Overrides javafx.scene.control.Control.layoutChildren.

Invoked during the layout pass to layout the children in this Parent.

public final ObjectProperty<EventHandler<TreeView.EditEvent<T>>>

Returns:

the event handler will be fired when the user cancels editing a cell
onEditCancelProperty
()

This event handler will be fired when the user cancels editing a cell.

public final ObjectProperty<EventHandler<TreeView.EditEvent<T>>>

Returns:

the event handler when the user performs an action that result in their editing input being persisted
onEditCommitProperty
()

This property is used when the user performs an action that should result in their editing input being persisted.

public final ObjectProperty<EventHandler<TreeView.EditEvent<T>>>

Returns:

the event handler when the user successfully initiates editing
onEditStartProperty
()

This event handler will be fired when the user successfully initiates editing.

public ObjectProperty<EventHandler<ScrollToEvent<Integer>>>
public Object
queryAccessibleAttribute(AccessibleAttribute
the requested attribute
attribute
,
Object...
optional list of parameters
parameters
)

Overrides javafx.scene.control.Control.queryAccessibleAttribute.

This method is called by the assistive technology to request the value for an attribute.

public void
refresh()

Calling refresh() forces the TreeView control to recreate and repopulate the cells necessary to populate the visual bounds of the control.

public final ObjectProperty<TreeItem<T>>

Returns:

the root node property
rootProperty
()

Property representing the root node of the TreeView.

public void
scrollTo(int
The index that should be made visible to the user, assuming of course that it is greater than, or equal to 0, and less than the number of the visible items in the TreeView.
index
)

Scrolls the TreeView such that the item in the given index is visible to the end user.

public final ObjectProperty<MultipleSelectionModel<TreeItem<T>>>

Returns:

the selection model property
selectionModelProperty
()

The SelectionModel provides the API through which it is possible to select single or multiple items within a TreeView, as well as inspect which rows have been selected by the user.

public final void
setCellFactory(Callback<TreeView<T>, TreeCell<T>>
The Callback to use for generating TreeCell instances, or null if the default cell factory should be used.
value
)

Sets the cell factory that will be used for creating TreeCells, which are used to represent items in the TreeView.

public final void
setEditable(boolean value)

private void
private void
public final void
setFixedCellSize(double
The new fixed cell size value, or a value less than or equal to zero (or Region.USE_COMPUTED_SIZE) to disable.
value
)

Sets the new fixed cell size for this control.

public final void
setFocusModel(FocusModel<TreeItem<T>>
the FocusModel to be used
value
)

Sets the FocusModel to be used in the TreeView.

public final void
setOnEditCancel(EventHandler<TreeView.EditEvent<T>>
the EventHandler that will be called when the user cancels an edit
value
)

Sets the EventHandler that will be called when the user cancels an edit.

public final void
setOnEditCommit(EventHandler<TreeView.EditEvent<T>>
the EventHandler that will be called when the user commits an edit
value
)

Sets the EventHandler that will be called when the user commits an edit.

public final void
setOnEditStart(EventHandler<TreeView.EditEvent<T>>
the EventHandler that will be called when the user begins an edit
value
)

Sets the EventHandler that will be called when the user begins an edit.

public void
public final void
setRoot(TreeItem<T>
The TreeItem that will be placed at the root of the TreeView.
value
)

Sets the root node in this TreeView.

public final void
setSelectionModel(MultipleSelectionModel<TreeItem<T>>
the MultipleSelectionModel to be used
value
)

Sets the MultipleSelectionModel to be used in the TreeView.

public final void
setShowRoot(boolean
If true, the root TreeItem will be shown, and if false it will be hidden.
value
)

Specifies whether the root TreeItem should be shown within this TreeView.

public final BooleanProperty

Returns:

the show root property
showRootProperty
()

Property that represents whether or not the TreeView root node is visible.

private void
private void
Inherited from javafx.scene.control.Control:
computeMaxHeightcomputeMaxWidthcomputeMinHeightcomputeMinWidthcomputePrefHeightcomputePrefWidthcontextMenuPropertyexecuteAccessibleActiongetBaselineOffsetgetContextMenugetControlChildrengetCssMetaDatagetInitialFocusTraversablegetSkingetTooltipisResizableloadSkinClasssetContextMenusetSkinsetTooltipskinClassNamePropertyskinPropertytooltipProperty