Class TreeView<T>

  • Type Parameters:
    T - The type of the item contained within the TreeItem value property for all tree items in this TreeView.
    All Implemented Interfaces:
    Styleable, EventTarget, Skinnable

    @DefaultProperty("root")
    public class TreeView<T>
    extends Control
    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<String>("Root Node");
     root.setExpanded(true);
     root.getChildren().addAll(
         new TreeItem<String>("Item 1"),
         new TreeItem<String>("Item 2"),
         new TreeItem<String>("Item 3")
     );
     TreeView<String> treeView = new TreeView<String>(root);
     

    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.

    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 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 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 TreeView.EditEvent that is fired. It is simply a matter of calling TreeView.EditEvent.getNewValue() to retrieve this value.

    It is very important to note that if you call 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 Node.addEventHandler(javafx.event.EventType, javafx.event.EventHandler) method to add a 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
    • Property Detail

      • cellFactory

        public final ObjectProperty<Callback<TreeView<T>,TreeCell<T>>> cellFactoryProperty
        Represents the cell factory that will be used for creating TreeCells, which are used to represent items in the TreeView.
        Returns:
        the cell factory property
      • expandedItemCount

        public final ReadOnlyIntegerProperty expandedItemCountProperty

        Represents the number of tree nodes presently able to be visible in the TreeView. This is essentially the count of all expanded tree items, and their children.

        For example, if just the root node is visible, the expandedItemCount will be one. If the root had three children and the root was expanded, the value will be four.

        Since:
        JavaFX 8.0
        See Also:
        getExpandedItemCount()
      • fixedCellSize

        public final DoubleProperty fixedCellSizeProperty
        Specifies whether this control has cells that are a fixed height (of the specified value). If this value is less than or equal to zero, then all cells are individually sized and positioned. This is a slow operation. Therefore, when performance matters and developers are not dependent on variable cell sizes it is a good idea to set the fixed cell size value. Generally cells are around 24px, so setting a fixed cell size of 24 is likely to result in very little difference in visuals, but a improvement to performance.

        To set this property via CSS, use the -fx-fixed-cell-size property. This should not be confused with the -fx-cell-size property. The difference between these two CSS properties is that -fx-cell-size will size all cells to the specified size, but it will not enforce that this is the only size (thus allowing for variable cell sizes, and preventing the performance gains from being possible). Therefore, when performance matters use -fx-fixed-cell-size, instead of -fx-cell-size. If both properties are specified in CSS, -fx-fixed-cell-size takes precedence.

        Since:
        JavaFX 8.0
        See Also:
        getFixedCellSize(), setFixedCellSize(double)
      • editable

        public final BooleanProperty 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.
        See Also:
        isEditable(), setEditable(boolean)
    • Constructor Detail

      • TreeView

        public TreeView()
        Creates an empty TreeView.

        Refer to the TreeView class documentation for details on the default state of other properties.

      • TreeView

        public TreeView​(TreeItem<T> root)
        Creates a TreeView with the provided root node.

        Refer to the TreeView class documentation for details on the default state of other properties.

        Parameters:
        root - The node to be the root in this TreeView.
    • Method Detail

      • editAnyEvent

        public static <T> EventType<TreeView.EditEvent<T>> editAnyEvent()
        An EventType that indicates some edit event has occurred. It is the parent type of all other edit events: editStartEvent(), editCommitEvent() and editCancelEvent().
        Type Parameters:
        T - the type of the TreeItem instances used in this TreeView
        Returns:
        An EventType that indicates some edit event has occurred.
      • editStartEvent

        public static <T> EventType<TreeView.EditEvent<T>> editStartEvent()
        An EventType used to indicate that an edit event has started within the TreeView upon which the event was fired.
        Type Parameters:
        T - the type of the TreeItem instances used in this TreeView
        Returns:
        An EventType used to indicate that an edit event has started.
      • editCancelEvent

        public static <T> EventType<TreeView.EditEvent<T>> editCancelEvent()
        An EventType used to indicate that an edit event has just been canceled within the TreeView upon which the event was fired.
        Type Parameters:
        T - the type of the TreeItem instances used in this TreeView
        Returns:
        An EventType used to indicate that an edit event has just been canceled.
      • editCommitEvent

        public static <T> EventType<TreeView.EditEvent<T>> editCommitEvent()
        An EventType that is used to indicate that an edit in a TreeView has been committed. This means that user has made changes to the data of a TreeItem, and that the UI should be updated.
        Type Parameters:
        T - the type of the TreeItem instances used in this TreeView
        Returns:
        An EventType that is used to indicate that an edit in a TreeView has been committed.
      • getNodeLevel

        @Deprecated(since="8u20")
        public static int getNodeLevel​(TreeItem<?> node)
        Deprecated.
        This method does not correctly calculate the distance from the given TreeItem to the root of the TreeView. As of JavaFX 8.0_20, the proper way to do this is via getTreeItemLevel(TreeItem)
        Returns the number of levels of 'indentation' of the given TreeItem, based on how many times TreeItem.getParent() can be recursively called. If the TreeItem does not have any parent set, the returned value will be zero. For each time getParent() is recursively called, the returned value is incremented by one.

        Important note: This method is deprecated as it does not consider the root node. This means that this method will iterate past the root node of the TreeView control, if the root node has a parent. If this is important, call getTreeItemLevel(TreeItem) instead.

        Parameters:
        node - The TreeItem for which the level is needed.
        Returns:
        An integer representing the number of parents above the given node, or -1 if the given TreeItem is null.
      • setCellFactory

        public final void setCellFactory​(Callback<TreeView<T>,TreeCell<T>> value)
        Sets the cell factory that will be used for creating TreeCells, which are used to represent items in the TreeView. The factory works identically to the cellFactory in ListView and other complex composite controls. It is called to create a new TreeCell only when the system has determined that it doesn't have enough cells to represent the currently visible items. The TreeCell is reused by the system to represent different items in the tree when possible.

        Refer to the Cell class documentation for more details.

        Parameters:
        value - The Callback to use for generating TreeCell instances, or null if the default cell factory should be used.
      • getCellFactory

        public final Callback<TreeView<T>,TreeCell<T>> 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.

        Returns:
        the cell factory
      • cellFactoryProperty

        public final ObjectProperty<Callback<TreeView<T>,TreeCell<T>>> cellFactoryProperty()
        Represents the cell factory that will be used for creating TreeCells, which are used to represent items in the TreeView.
        Returns:
        the cell factory property
      • setRoot

        public final void setRoot​(TreeItem<T> value)
        Sets the root node in this TreeView. See the TreeItem class level documentation for more details.
        Parameters:
        value - The TreeItem that will be placed at the root of the TreeView.
      • getRoot

        public final TreeItem<T> getRoot()
        Returns the current root node of this TreeView, or null if no root node is specified.
        Returns:
        The current root node, or null if no root node exists.
      • setShowRoot

        public final void setShowRoot​(boolean value)
        Specifies whether the root TreeItem should be shown within this TreeView.
        Parameters:
        value - If true, the root TreeItem will be shown, and if false it will be hidden.
      • isShowRoot

        public final boolean isShowRoot()
        Returns true if the root of the TreeView should be shown, and false if it should not. By default, the root TreeItem is visible in the TreeView.
        Returns:
        true if the root of the TreeView should be shown
      • getSelectionModel

        public final MultipleSelectionModel<TreeItem<T>> getSelectionModel()
        Returns the currently installed selection model.
        Returns:
        the currently installed selection model
      • expandedItemCountProperty

        public final ReadOnlyIntegerProperty expandedItemCountProperty()

        Represents the number of tree nodes presently able to be visible in the TreeView. This is essentially the count of all expanded tree items, and their children.

        For example, if just the root node is visible, the expandedItemCount will be one. If the root had three children and the root was expanded, the value will be four.

        Since:
        JavaFX 8.0
        See Also:
        getExpandedItemCount()
      • getExpandedItemCount

        public final int getExpandedItemCount()
        Gets the value of the property expandedItemCount.
        Property description:

        Represents the number of tree nodes presently able to be visible in the TreeView. This is essentially the count of all expanded tree items, and their children.

        For example, if just the root node is visible, the expandedItemCount will be one. If the root had three children and the root was expanded, the value will be four.

        Since:
        JavaFX 8.0
      • setFixedCellSize

        public final void setFixedCellSize​(double value)
        Sets the new fixed cell size for this control. Any value greater than zero will enable fixed cell size mode, whereas a zero or negative value (or Region.USE_COMPUTED_SIZE) will be used to disabled fixed cell size mode.
        Parameters:
        value - The new fixed cell size value, or a value less than or equal to zero (or Region.USE_COMPUTED_SIZE) to disable.
        Since:
        JavaFX 8.0
      • getFixedCellSize

        public final double getFixedCellSize()
        Returns the fixed cell size value. A value less than or equal to zero is used to represent that fixed cell size mode is disabled, and a value greater than zero represents the size of all cells in this control.
        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.
        Since:
        JavaFX 8.0
      • fixedCellSizeProperty

        public final DoubleProperty fixedCellSizeProperty()
        Specifies whether this control has cells that are a fixed height (of the specified value). If this value is less than or equal to zero, then all cells are individually sized and positioned. This is a slow operation. Therefore, when performance matters and developers are not dependent on variable cell sizes it is a good idea to set the fixed cell size value. Generally cells are around 24px, so setting a fixed cell size of 24 is likely to result in very little difference in visuals, but a improvement to performance.

        To set this property via CSS, use the -fx-fixed-cell-size property. This should not be confused with the -fx-cell-size property. The difference between these two CSS properties is that -fx-cell-size will size all cells to the specified size, but it will not enforce that this is the only size (thus allowing for variable cell sizes, and preventing the performance gains from being possible). Therefore, when performance matters use -fx-fixed-cell-size, instead of -fx-cell-size. If both properties are specified in CSS, -fx-fixed-cell-size takes precedence.

        Since:
        JavaFX 8.0
        See Also:
        getFixedCellSize(), setFixedCellSize(double)
      • setEditable

        public final void setEditable​(boolean value)
        Sets the value of the property editable.
        Property description:
        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.
      • isEditable

        public final boolean isEditable()
        Gets the value of the property editable.
        Property description:
        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.
      • editableProperty

        public final BooleanProperty 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.
        See Also:
        isEditable(), setEditable(boolean)
      • getEditingItem

        public final TreeItem<T> getEditingItem()
        Returns the TreeItem that is currently being edited in the TreeView, or null if no item is being edited.
        Returns:
        the TreeItem that is currently being edited in the TreeView
      • edit

        public void edit​(TreeItem<T> item)
        Instructs the TreeView to begin editing the given TreeItem, if the TreeView is editable. Once this method is called, if the current cell factory is set up to support editing, the Cell will switch its visual state to enable the user input to take place.
        Parameters:
        item - The TreeItem in the TreeView that should be edited.
      • scrollTo

        public void scrollTo​(int index)
        Scrolls the TreeView such that the item in the given index is visible to the end user.
        Parameters:
        index - 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.
      • setOnScrollTo

        public void setOnScrollTo​(EventHandler<ScrollToEvent<Integer>> value)
        Sets the value of the property onScrollTo.
        Property description:
        Called when there's a request to scroll an index into view using scrollTo(int)
        Since:
        JavaFX 8.0
      • getOnScrollTo

        public EventHandler<ScrollToEvent<Integer>> getOnScrollTo()
        Gets the value of the property onScrollTo.
        Property description:
        Called when there's a request to scroll an index into view using scrollTo(int)
        Since:
        JavaFX 8.0
      • getRow

        public int getRow​(TreeItem<T> 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). If a parent tree item is collapsed, the result is that this method will return -1 to indicate that the given tree item is not accessible in the tree.
        Parameters:
        item - The TreeItem for which the index is sought.
        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).
      • getTreeItem

        public TreeItem<T> getTreeItem​(int row)
        Returns the TreeItem in the given index, or null if it is out of bounds.
        Parameters:
        row - The index of the TreeItem being sought.
        Returns:
        The TreeItem in the given index, or null if it is out of bounds.
      • getTreeItemLevel

        public int getTreeItemLevel​(TreeItem<?> node)
        Returns the number of levels of 'indentation' of the given TreeItem, based on how many times getParent() can be recursively called. If the given TreeItem is the root node of this TreeView, or if the TreeItem does not have any parent set, the returned value will be zero. For each time getParent() is recursively called, the returned value is incremented by one.
        Parameters:
        node - The TreeItem for which the level is needed.
        Returns:
        An integer representing the number of parents above the given node, or -1 if the given TreeItem is null.
      • refresh

        public void refresh()
        Calling refresh() forces the TreeView control to recreate and repopulate the cells necessary to populate the visual bounds of the control. In other words, this forces the TreeView to update what it is showing to the user. This is useful in cases where the underlying data source has changed in a way that is not observed by the TreeView itself.
        Since:
        JavaFX 8u60
      • getClassCssMetaData

        public static List<CssMetaData<? extends Styleable,?>> getClassCssMetaData()
        Returns:
        The CssMetaData associated with this class, which may include the CssMetaData of its superclasses.
        Since:
        JavaFX 8.0