items ObservableList. It is
also used in the selection model
and focus model.
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.
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);
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.
ListView allows for the items list to contain elements of any type, including
Node instances. Putting nodes into
the items list is strongly discouraged, as it can
lead to unexpected results.
Important points to note:
Node instances directly into the items list or its data model.cell factory to create the nodes for a
given cell and update them on demand using the data stored in the item for that cell.Nodes in the updateItem method of a custom cell factory.The following minimal example shows how to create a custom cell factory for ListView containing Nodes:
ListView<Color> lv = new ListView<>();
lv.getItems().addAll(Color.RED, Color.GREEN, Color.BLUE);
lv.setCellFactory(p -> {
return new ListCell<>() {
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 ListCell 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 ListCell class and updated/used in its updateItem method.
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 javafx. 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
ListView#setOnEditCommit(javafx.. 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
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
ListView#setOnEditCommit(javafx. 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
ListView#addEventHandler(javafx.
method to add a ListView#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.
ListCell, MultipleSelectionModel, FocusModel
| Modifier and Type | Class and Description |
|---|---|
| public static class | ListView.
The type of the input, which is the same type as the ListView
itself. T>An |
| pack-priv static class | |
| pack-priv static class | |
| private static class |
| Modifier and Type | Field and Description |
|---|---|
| private ObjectProperty | |
| private EventHandler | |
| private static final String | |
| private static final EventType | |
| private static final EventType | |
| private static final EventType | |
| private static final EventType | |
| private BooleanProperty | |
| private ReadOnlyIntegerWrapper | |
| private DoubleProperty | |
| private ObjectProperty | |
| private ObjectProperty | |
| private ObjectProperty | |
| private ObjectProperty | |
| private ObjectProperty | |
| private ObjectProperty | onScrollTo
Called when there's a request to scroll an index into view using |
| private ObjectProperty | |
| private ObjectProperty | placeholder
The |
| private static final PseudoClass | |
| private static final PseudoClass | |
| private boolean | |
| private ObjectProperty |
| Access | Constructor and Description |
|---|---|
| public | |
| public | ListView(ObservableList<T>
the list of items items)Creates a default ListView which will stack the contents retrieved from the
provided |
| Modifier and Type | Method and Description |
|---|---|
| public final ObjectProperty | Returns: the cell factory propertySetting a custom cell factory has the effect of deferring all cell creation, allowing for total customization of the cell. |
| protected Skin | createDefaultSkin()
Overrides javafx. Create a new instance of the default skin for this control. |
| public void | |
| public final BooleanProperty | Returns: the editable propertySpecifies 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. |
| public static < the type of the objects stored in this ListView T> EventType | |
| public static < the type of the objects stored in this ListView T> EventType | Returns: the event typeAn EventType used to indicate that an edit event has just been canceled within the ListView upon which the event was fired. |
| public static < the type of the objects stored in this ListView T> EventType | Returns: the event typeAn EventType used to indicate that an edit event has been committed within the ListView upon which the event was fired. |
| public final ReadOnlyIntegerProperty | Returns: the editing index propertyA 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. |
| private ReadOnlyIntegerWrapper | |
| public static < the type of the objects stored in this ListView T> EventType | Returns: the event typeAn EventType used to indicate that an edit event has started within the ListView upon which the event was fired. |
| public final DoubleProperty | Returns: the fixed cell size propertySpecifies whether this control has cells that are a fixed height (of the specified value). |
| public final ObjectProperty | Returns: the FocusModel propertyThe FocusModel provides the API through which it is possible to both get and set the focus on a single item within a ListView. |
| public final Callback | |
| public static List | Returns: theCssMetaDataHides javafx. Gets the |
| public List | getControlCssMetaData()
Overrides javafx. Gets the unmodifiable list of the control's CSS-styleable properties. |
| public final int | Returns: the index of the item currently being editedReturns the index of the item currently being edited in the ListView, or -1 if no item is being edited. |
| 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.Returns the fixed cell size value. |
| public final FocusModel | Returns: the currently installed FocusModelReturns the currently installed |
| public final ObservableList | Returns: An ObservableList containing the items to be shown to the user, or null if the items have previously been set to null.Returns an |
| public final EventHandler | Returns: the EventHandler that will be called when the user cancels an editReturns the |
| public final EventHandler | Returns: the EventHandler that will be called when the user commits an editReturns the |
| public final EventHandler | Returns: the EventHandler that will be called when the user begins an editReturns the |
| public final EventHandler | |
| public final Orientation | Returns: the current orientation of the ListViewReturns the current orientation of the ListView, which dictates whether it scrolls vertically or horizontally. |
| public final Node | |
| public final MultipleSelectionModel | Returns: the currently installed selection modelReturns the currently installed selection model. |
| public final boolean | |
| public final ObjectProperty | Returns: the items property for this ListViewThe underlying data model for the ListView. |
| public final ObjectProperty | Returns: the onEditCancel event handler propertyThis event handler will be fired when the user cancels editing a cell. |
| public final ObjectProperty | Returns: the onEditCommit event handler propertyThis property is used when the user performs an action that should result in their editing input being persisted. |
| public final ObjectProperty | Returns: the onEditStart event handler propertyThis event handler will be fired when the user successfully initiates editing. |
| public final ObjectProperty | |
| public final ObjectProperty | Returns: the orientation property of this ListViewThe orientation of the |
| public final ObjectProperty | |
| public Object | queryAccessibleAttribute(AccessibleAttribute
the requested attribute attribute, Object... optional list of parameters parameters)Overrides javafx. This method is called by the assistive technology to request the value for an attribute. |
| public void | refresh()
Calling |
| 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
size of the items list contained within the given ListView. index)Scrolls the ListView such that the item in the given index is visible to the end user. |
| public void | scrollTo(T
The object that should be visible to the user. object)Scrolls the ListView so that the given object is visible within the viewport. |
| public final ObjectProperty | Returns: the selectionModel propertyThe SelectionModel provides the API through which it is possible to select single or multiple items within a ListView, as well as inspect which items have been selected by the user. |
| public final void | setCellFactory(Callback<ListView<T>, ListCell<T>>
cell factory to use in this ListView value)Sets a new cell factory to use in the ListView. |
| public final 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<T>
the FocusModel to be used in the ListView value)Sets the |
| public final void | setItems(ObservableList<T>
the list of items for this ListView value)Sets the underlying data model for the ListView. |
| public final void | setOnEditCancel(EventHandler<ListView.
the EventHandler that will be called when the user cancels
an edit valueSets the |
| public final void | setOnEditCommit(EventHandler<ListView.
the EventHandler that will be called when the user has
completed their editing valueSets the |
| public final void | setOnEditStart(EventHandler<ListView.
the EventHandler that will be called when the user begins
an edit valueSets the |
| public final void | |
| public final void | setOrientation(Orientation
the orientation of the ListView value)Sets the orientation of the ListView, which dictates whether it scrolls vertically or horizontally. |
| public final void | |
| public final void | setSelectionModel(MultipleSelectionModel<T>
the MultipleSelectionModel to be used in this ListView value)Sets the |