Class ListView<T>

  • Type Parameters:
    T - This type is used to represent the type of the objects stored in the ListViews items ObservableList. It is also used in the selection model and focus model.
    All Implemented Interfaces:
    Styleable, EventTarget, Skinnable

    @DefaultProperty("items")
    public class ListView<T>
    extends Control
    A ListView displays a horizontal or vertical list of items from which the user may select, or with which the user may interact. A ListView is able to have its generic type set to represent the type of data in the backing model. Doing this has the benefit of making various methods in the ListView, as well as the supporting classes (mentioned below), type-safe. In addition, making use of the generic type supports substantially simplified development of applications making use of ListView, as all modern IDEs are able to auto-complete far more successfully with the additional type information.

    Populating a ListView

    A simple example of how to create and populate a ListView of names (Strings) is shown here:

     
     ObservableList<String> names = FXCollections.observableArrayList(
              "Julia", "Ian", "Sue", "Matthew", "Hannah", "Stephan", "Denise");
     ListView<String> listView = new ListView<String>(names);

    The elements of the ListView are contained within the items ObservableList. This ObservableList is automatically observed by the ListView, such that any changes that occur inside the ObservableList will be automatically shown in the ListView itself. If passing the ObservableList in to the ListView constructor is not feasible, the recommended approach for setting the items is to simply call:

     
     ObservableList<T> content = ...
     listView.setItems(content);
    The end result of this is, as noted above, that the ListView will automatically refresh the view to represent the items in the list.

    Another approach, whilst accepted by the ListView, is not the recommended approach:

     
     List<T> content = ...
     getItems().setAll(content);
    The issue with the approach shown above is that the content list is being copied into the items list - meaning that subsequent changes to the content list are not observed, and will not be reflected visually within the ListView.

    ListView Selection / Focus APIs

    To track selection and focus, it is necessary to become familiar with the SelectionModel and FocusModel classes. A ListView 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 ListView 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 ListView instance, it is therefore necessary to do the following:

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

    Customizing ListView Visuals

    The visuals of the ListView can be entirely customized by replacing the default cell factory. A cell factory is used to generate ListCell instances, which are used to represent an item in the ListView. 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 ListView, 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 ListView, 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 ListView 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 ListView.EditEvent that is fired. It is simply a matter of calling ListView.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:
    ListCell, MultipleSelectionModel, FocusModel
    • Property Detail

      • items

        public final ObjectProperty<ObservableList<T>> itemsProperty
        The underlying data model for the ListView. Note that it has a generic type that must match the type of the ListView itself.
        Returns:
        the items property for this ListView
      • placeholder

        public final ObjectProperty<Node> placeholderProperty
        This Node is shown to the user when the listview has no content to show. This may be the case because the table model has no data in the first place or that a filter has been applied to the list model, resulting in there being nothing to show the user..
        Since:
        JavaFX 8.0
        See Also:
        getPlaceholder(), setPlaceholder(Node)
      • focusModel

        public final ObjectProperty<FocusModel<T>> focusModelProperty
        The FocusModel provides the API through which it is possible to both get and set the focus on a single item within a ListView. Note that it has a generic type that must match the type of the ListView itself.
        See Also:
        getFocusModel(), setFocusModel(FocusModel)
      • cellFactory

        public final ObjectProperty<Callback<ListView<T>,​ListCell<T>>> cellFactoryProperty

        Setting a custom cell factory has the effect of deferring all cell creation, allowing for total customization of the cell. Internally, the ListView is responsible for reusing ListCells - all that is necessary is for the custom cell factory to return from this function a ListCell which might be usable for representing any item in the ListView.

        Refer to the Cell class documentation for more detail.

        See Also:
        getCellFactory(), setCellFactory(Callback)
      • 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 ListView is editable - only if the ListView and the ListCells within it are both editable will a ListCell be able to go into their editing state.
        See Also:
        isEditable(), setEditable(boolean)
      • editingIndex

        public final ReadOnlyIntegerProperty editingIndexProperty

        A property used to represent the index of the item currently being edited in the ListView, if editing is taking place, or -1 if no item is being edited.

        It is not possible to set the editing index, instead it is required that you call edit(int).

        See Also:
        getEditingIndex()
    • Constructor Detail

      • ListView

        public ListView()
        Creates a default ListView which will display contents stacked vertically. As no ObservableList is provided in this constructor, an empty ObservableList is created, meaning that it is legal to directly call getItems() if so desired. However, as noted elsewhere, this is not the recommended approach (instead call setItems(javafx.collections.ObservableList)).

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

      • ListView

        public ListView​(ObservableList<T> items)
        Creates a default ListView which will stack the contents retrieved from the provided ObservableList vertically.

        Attempts to add a listener to the ObservableList, such that all subsequent changes inside the list will be shown to the user.

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

        Parameters:
        items - the list of items
    • Method Detail

      • editStartEvent

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

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

        public static <T> EventType<ListView.EditEvent<T>> editCommitEvent()
        An EventType used to indicate that an edit event has been committed within the ListView upon which the event was fired.
        Type Parameters:
        T - the type of the objects stored in this ListView
        Returns:
        the event type
      • setItems

        public final void setItems​(ObservableList<T> value)
        Sets the underlying data model for the ListView. Note that it has a generic type that must match the type of the ListView itself.
        Parameters:
        value - the list of items for this ListView
      • getItems

        public final ObservableList<T> getItems()
        Returns an ObservableList that contains the items currently being shown to the user. This may be null if setItems(javafx.collections.ObservableList) has previously been called, however, by default it is an empty ObservableList.
        Returns:
        An ObservableList containing the items to be shown to the user, or null if the items have previously been set to null.
      • itemsProperty

        public final ObjectProperty<ObservableList<T>> itemsProperty()
        The underlying data model for the ListView. Note that it has a generic type that must match the type of the ListView itself.
        Returns:
        the items property for this ListView
      • placeholderProperty

        public final ObjectProperty<Node> placeholderProperty()
        This Node is shown to the user when the listview has no content to show. This may be the case because the table model has no data in the first place or that a filter has been applied to the list model, resulting in there being nothing to show the user..
        Since:
        JavaFX 8.0
        See Also:
        getPlaceholder(), setPlaceholder(Node)
      • setPlaceholder

        public final void setPlaceholder​(Node value)
        Sets the value of the property placeholder.
        Property description:
        This Node is shown to the user when the listview has no content to show. This may be the case because the table model has no data in the first place or that a filter has been applied to the list model, resulting in there being nothing to show the user..
        Since:
        JavaFX 8.0
      • getPlaceholder

        public final Node getPlaceholder()
        Gets the value of the property placeholder.
        Property description:
        This Node is shown to the user when the listview has no content to show. This may be the case because the table model has no data in the first place or that a filter has been applied to the list model, resulting in there being nothing to show the user..
        Since:
        JavaFX 8.0
      • getSelectionModel

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

        public final void setFocusModel​(FocusModel<T> value)
        Sets the FocusModel to be used in the ListView.
        Parameters:
        value - the FocusModel to be used in the ListView
      • getFocusModel

        public final FocusModel<T> getFocusModel()
        Returns the currently installed FocusModel.
        Returns:
        the currently installed FocusModel
      • focusModelProperty

        public final ObjectProperty<FocusModel<T>> focusModelProperty()
        The FocusModel provides the API through which it is possible to both get and set the focus on a single item within a ListView. Note that it has a generic type that must match the type of the ListView itself.
        See Also:
        getFocusModel(), setFocusModel(FocusModel)
      • setOrientation

        public final void setOrientation​(Orientation value)
        Sets the orientation of the ListView, which dictates whether it scrolls vertically or horizontally.
        Parameters:
        value - the orientation of the ListView
      • getOrientation

        public final Orientation getOrientation()
        Returns the current orientation of the ListView, which dictates whether it scrolls vertically or horizontally.
        Returns:
        the current orientation of the ListView
      • setCellFactory

        public final void setCellFactory​(Callback<ListView<T>,​ListCell<T>> value)
        Sets a new cell factory to use in the ListView. This forces all old ListCell's to be thrown away, and new ListCell's created with the new cell factory.
        Parameters:
        value - cell factory to use in this ListView
      • getCellFactory

        public final Callback<ListView<T>,​ListCell<T>> getCellFactory()
        Returns the current cell factory.
        Returns:
        the current cell factory
      • cellFactoryProperty

        public final ObjectProperty<Callback<ListView<T>,​ListCell<T>>> cellFactoryProperty()

        Setting a custom cell factory has the effect of deferring all cell creation, allowing for total customization of the cell. Internally, the ListView is responsible for reusing ListCells - all that is necessary is for the custom cell factory to return from this function a ListCell which might be usable for representing any item in the ListView.

        Refer to the Cell class documentation for more detail.

        See Also:
        getCellFactory(), setCellFactory(Callback)
      • 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 ListView is editable - only if the ListView and the ListCells within it are both editable will a ListCell 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 ListView is editable - only if the ListView and the ListCells within it are both editable will a ListCell be able to go into their editing state.
      • editableProperty

        public final BooleanProperty editableProperty()
        Specifies whether this ListView is editable - only if the ListView and the ListCells within it are both editable will a ListCell be able to go into their editing state.
        See Also:
        isEditable(), setEditable(boolean)
      • getEditingIndex

        public final int getEditingIndex()
        Returns the index of the item currently being edited in the ListView, or -1 if no item is being edited.
        Returns:
        the index of the item currently being edited
      • editingIndexProperty

        public final ReadOnlyIntegerProperty editingIndexProperty()

        A property used to represent the index of the item currently being edited in the ListView, if editing is taking place, or -1 if no item is being edited.

        It is not possible to set the editing index, instead it is required that you call edit(int).

        See Also:
        getEditingIndex()
      • setOnEditStart

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

        This is a convenience method - the same result can be achieved by calling addEventHandler(ListView.EDIT_START_EVENT, eventHandler).

        Parameters:
        value - the EventHandler that will be called when the user begins an edit
      • getOnEditStart

        public final EventHandler<ListView.EditEvent<T>> getOnEditStart()
        Returns the EventHandler that will be called when the user begins an edit.
        Returns:
        the EventHandler that will be called when the user begins an edit
      • setOnEditCommit

        public final void setOnEditCommit​(EventHandler<ListView.EditEvent<T>> value)
        Sets the EventHandler that will be called when the user has completed their editing. This is called as part of the ListCell.commitEdit(java.lang.Object) method.

        This is a convenience method - the same result can be achieved by calling addEventHandler(ListView.EDIT_START_EVENT, eventHandler).

        Parameters:
        value - the EventHandler that will be called when the user has completed their editing
      • getOnEditCommit

        public final EventHandler<ListView.EditEvent<T>> getOnEditCommit()
        Returns the EventHandler that will be called when the user commits an edit.
        Returns:
        the EventHandler that will be called when the user commits an edit
      • setOnEditCancel

        public final void setOnEditCancel​(EventHandler<ListView.EditEvent<T>> value)
        Sets the EventHandler that will be called when the user cancels an edit.
        Parameters:
        value - the EventHandler that will be called when the user cancels an edit
      • getOnEditCancel

        public final EventHandler<ListView.EditEvent<T>> getOnEditCancel()
        Returns the EventHandler that will be called when the user cancels an edit.
        Returns:
        the EventHandler that will be called when the user cancels an edit
      • edit

        public void edit​(int itemIndex)
        Instructs the ListView to begin editing the item in the given index, if the ListView is editable. Once this method is called, if the current cellFactoryProperty() is set up to support editing, the Cell will switch its visual state to enable for user input to take place.
        Parameters:
        itemIndex - The index of the item in the ListView that should be edited.
      • scrollTo

        public void scrollTo​(int index)
        Scrolls the ListView 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 size of the items list contained within the given ListView.
      • scrollTo

        public void scrollTo​(T object)
        Scrolls the ListView so that the given object is visible within the viewport.
        Parameters:
        object - The object that should be visible to the user.
        Since:
        JavaFX 8.0
      • createDefaultSkin

        protected Skin<?> createDefaultSkin()
        Create a new instance of the default skin for this control. This is called to create a skin for the control if no skin is provided via CSS -fx-skin or set explicitly in a sub-class with setSkin(...).
        Overrides:
        createDefaultSkin in class Control
        Returns:
        new instance of default skin for this control. If null then the control will have no skin unless one is provided by css.
      • refresh

        public void refresh()
        Calling refresh() forces the ListView control to recreate and repopulate the cells necessary to populate the visual bounds of the control. In other words, this forces the ListView 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 ListView 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
      • queryAccessibleAttribute

        public Object queryAccessibleAttribute​(AccessibleAttribute attribute,
                                               Object... parameters)
        This method is called by the assistive technology to request the value for an attribute.

        This method is commonly overridden by subclasses to implement attributes that are required for a specific role.
        If a particular attribute is not handled, the superclass implementation must be called.

        Overrides:
        queryAccessibleAttribute in class Control
        Parameters:
        attribute - the requested attribute
        parameters - optional list of parameters
        Returns:
        the value for the requested attribute
        See Also:
        AccessibleAttribute