- Type Parameters:
T- This type is used to represent the type of the objects stored in the ListViewsitemsObservableList. It is also used in theselection modelandfocus model.
- All Implemented Interfaces:
Styleable,EventTarget,Skinnable
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.
Warning: Nodes should not be inserted directly into the items list
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:
- Avoid inserting
Nodeinstances directly into the items list or its data model. - The recommended approach is to put the relevant information into the items list, and
provide a custom
cell factoryto create the nodes for a given cell and update them on demand using the data stored in the item for that cell. - Avoid creating new
Nodes in theupdateItemmethod of a customcell 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.
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:
-
Property Summary
PropertiesTypePropertyDescriptionSetting a custom cell factory has the effect of deferring all cell creation, allowing for total customization of the cell.final BooleanPropertySpecifies 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.final ReadOnlyIntegerPropertyA 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.final DoublePropertySpecifies whether this control has cells that are a fixed height (of the specified value).final ObjectProperty<FocusModel<T>>The FocusModel provides the API through which it is possible to both get and set the focus on a single item within a ListView.final ObjectProperty<ObservableList<T>>The underlying data model for the ListView.final ObjectProperty<EventHandler<ListView.EditEvent<T>>>This event handler will be fired when the user cancels editing a cell.final ObjectProperty<EventHandler<ListView.EditEvent<T>>>This property is used when the user performs an action that should result in their editing input being persisted.final ObjectProperty<EventHandler<ListView.EditEvent<T>>>This event handler will be fired when the user successfully initiates editing.Called when there's a request to scroll an index into view usingscrollTo(int)orscrollTo(Object)final ObjectProperty<Orientation>The orientation of theListView- this can either be horizontal or vertical.final ObjectProperty<Node>TheNodeto show to the user when theListViewhas no content to show.final ObjectProperty<MultipleSelectionModel<T>>The 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.Properties declared in class javafx.scene.control.Control
contextMenu, skin, tooltipProperties declared in class javafx.scene.layout.Region
background, border, cacheShape, centerShape, height, insets, maxHeight, maxWidth, minHeight, minWidth, opaqueInsets, padding, prefHeight, prefWidth, scaleShape, shape, snapToPixel, widthProperties declared in class javafx.scene.Parent
needsLayoutProperties declared in class javafx.scene.Node
accessibleHelp, accessibleRoleDescription, accessibleRole, accessibleText, blendMode, boundsInLocal, boundsInParent, cacheHint, cache, clip, cursor, depthTest, disabled, disable, effectiveNodeOrientation, effect, eventDispatcher, focused, focusTraversable, focusVisible, focusWithin, hover, id, inputMethodRequests, layoutBounds, layoutX, layoutY, localToParentTransform, localToSceneTransform, managed, mouseTransparent, nodeOrientation, onContextMenuRequested, onDragDetected, onDragDone, onDragDropped, onDragEntered, onDragExited, onDragOver, onInputMethodTextChanged, onKeyPressed, onKeyReleased, onKeyTyped, onMouseClicked, onMouseDragEntered, onMouseDragExited, onMouseDragged, onMouseDragOver, onMouseDragReleased, onMouseEntered, onMouseExited, onMouseMoved, onMousePressed, onMouseReleased, onRotate, onRotationFinished, onRotationStarted, onScrollFinished, onScroll, onScrollStarted, onSwipeDown, onSwipeLeft, onSwipeRight, onSwipeUp, onTouchMoved, onTouchPressed, onTouchReleased, onTouchStationary, onZoomFinished, onZoom, onZoomStarted, opacity, parent, pickOnBounds, pressed, rotate, rotationAxis, scaleX, scaleY, scaleZ, scene, style, translateX, translateY, translateZ, viewOrder, visible -
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classAnEventsubclass used specifically in ListView for representing edit-related events. -
Field Summary
Fields declared in class javafx.scene.layout.Region
USE_COMPUTED_SIZE, USE_PREF_SIZEFields declared in class javafx.scene.Node
BASELINE_OFFSET_SAME_AS_HEIGHT -
Constructor Summary
ConstructorsConstructorDescriptionListView()Creates a default ListView which will display contents stacked vertically.ListView(ObservableList<T> items) Creates a default ListView which will stack the contents retrieved from the providedObservableListvertically. -
Method Summary
Modifier and TypeMethodDescriptionSetting a custom cell factory has the effect of deferring all cell creation, allowing for total customization of the cell.voidedit(int itemIndex) Instructs the ListView to begin editing the item in the given index, if the ListView iseditable.final BooleanPropertySpecifies 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.static <T> EventType<ListView.EditEvent<T>>An EventType that indicates some edit event has occurred.static <T> EventType<ListView.EditEvent<T>>An EventType used to indicate that an edit event has just been canceled within the ListView upon which the event was fired.static <T> EventType<ListView.EditEvent<T>>An EventType used to indicate that an edit event has been committed within the ListView upon which the event was fired.final ReadOnlyIntegerPropertyA 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.static <T> EventType<ListView.EditEvent<T>>An EventType used to indicate that an edit event has started within the ListView upon which the event was fired.final DoublePropertySpecifies whether this control has cells that are a fixed height (of the specified value).final ObjectProperty<FocusModel<T>>The FocusModel provides the API through which it is possible to both get and set the focus on a single item within a ListView.Returns the current cell factory.static List<CssMetaData<? extends Styleable,?>> Gets theCssMetaDataassociated with this class, which may include theCssMetaDataof its superclasses.List<CssMetaData<? extends Styleable,?>> Gets the unmodifiable list of the control's CSS-styleable properties.final intReturns the index of the item currently being edited in the ListView, or -1 if no item is being edited.final doubleReturns the fixed cell size value.final FocusModel<T>Returns the currently installedFocusModel.final ObservableList<T>getItems()Returns anObservableListthat contains the items currently being shown to the user.final EventHandler<ListView.EditEvent<T>>Returns theEventHandlerthat will be called when the user cancels an edit.final EventHandler<ListView.EditEvent<T>>Returns theEventHandlerthat will be called when the user commits an edit.final EventHandler<ListView.EditEvent<T>>Returns theEventHandlerthat will be called when the user begins an edit.Gets the value of theonScrollToproperty.final OrientationReturns the current orientation of the ListView, which dictates whether it scrolls vertically or horizontally.final NodeGets the value of theplaceholderproperty.final MultipleSelectionModel<T>Returns the currently installed selection model.final booleanGets the value of theeditableproperty.final ObjectProperty<ObservableList<T>>The underlying data model for the ListView.final ObjectProperty<EventHandler<ListView.EditEvent<T>>>This event handler will be fired when the user cancels editing a cell.final ObjectProperty<EventHandler<ListView.EditEvent<T>>>This property is used when the user performs an action that should result in their editing input being persisted.final ObjectProperty<EventHandler<ListView.EditEvent<T>>>This event handler will be fired when the user successfully initiates editing.Called when there's a request to scroll an index into view usingscrollTo(int)orscrollTo(Object)final ObjectProperty<Orientation>The orientation of theListView- this can either be horizontal or vertical.final ObjectProperty<Node>TheNodeto show to the user when theListViewhas no content to show.voidrefresh()Callingrefresh()forces the ListView control to recreate and repopulate the cells necessary to populate the visual bounds of the control.voidscrollTo(int index) Scrolls the ListView such that the item in the given index is visible to the end user.voidScrolls the ListView so that the given object is visible within the viewport.final ObjectProperty<MultipleSelectionModel<T>>The 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.final voidSets a new cell factory to use in the ListView.final voidsetEditable(boolean value) Sets the value of theeditableproperty.final voidsetFixedCellSize(double value) Sets the new fixed cell size for this control.final voidsetFocusModel(FocusModel<T> value) Sets theFocusModelto be used in the ListView.final voidsetItems(ObservableList<T> value) Sets the underlying data model for the ListView.final voidsetOnEditCancel(EventHandler<ListView.EditEvent<T>> value) Sets theEventHandlerthat will be called when the user cancels an edit.final voidsetOnEditCommit(EventHandler<ListView.EditEvent<T>> value) Sets theEventHandlerthat will be called when the user has completed their editing.final voidsetOnEditStart(EventHandler<ListView.EditEvent<T>> value) Sets theEventHandlerthat will be called when the user begins an edit.voidsetOnScrollTo(EventHandler<ScrollToEvent<Integer>> value) Sets the value of theonScrollToproperty.final voidsetOrientation(Orientation value) Sets the orientation of the ListView, which dictates whether it scrolls vertically or horizontally.final voidsetPlaceholder(Node value) Sets the value of theplaceholderproperty.final voidsetSelectionModel(MultipleSelectionModel<T> value) Sets theMultipleSelectionModelto be used in the ListView.Methods declared in class javafx.scene.control.Control
computeMaxHeight, computeMaxWidth, computeMinHeight, computeMinWidth, contextMenuProperty, createDefaultSkin, getContextMenu, getCssMetaData, getInitialFocusTraversable, getSkin, getTooltip, isResizable, setContextMenu, setSkin, setTooltip, skinProperty, tooltipPropertyMethods declared in class javafx.scene.layout.Region
backgroundProperty, borderProperty, cacheShapeProperty, centerShapeProperty, computePrefHeight, computePrefWidth, getBackground, getBorder, getHeight, getInsets, getMaxHeight, getMaxWidth, getMinHeight, getMinWidth, getOpaqueInsets, getPadding, getPrefHeight, getPrefWidth, getShape, getUserAgentStylesheet, getWidth, heightProperty, insetsProperty, isCacheShape, isCenterShape, isScaleShape, isSnapToPixel, layoutInArea, layoutInArea, layoutInArea, layoutInArea, maxHeight, maxHeightProperty, maxWidth, maxWidthProperty, minHeight, minHeightProperty, minWidth, minWidthProperty, opaqueInsetsProperty, paddingProperty, positionInArea, positionInArea, prefHeight, prefHeightProperty, prefWidth, prefWidthProperty, resize, scaleShapeProperty, setBackground, setBorder, setCacheShape, setCenterShape, setHeight, setMaxHeight, setMaxSize, setMaxWidth, setMinHeight, setMinSize, setMinWidth, setOpaqueInsets, setPadding, setPrefHeight, setPrefSize, setPrefWidth, setScaleShape, setShape, setSnapToPixel, setWidth, shapeProperty, snappedBottomInset, snappedLeftInset, snappedRightInset, snappedTopInset, snapPosition, snapPositionX, snapPositionY, snapSize, snapSizeX, snapSizeY, snapSpace, snapSpaceX, snapSpaceY, snapToPixelProperty, widthPropertyMethods declared in class javafx.scene.Parent
getBaselineOffset, getChildren, getChildrenUnmodifiable, getManagedChildren, getStylesheets, isNeedsLayout, layout, layoutChildren, needsLayoutProperty, requestLayout, requestParentLayout, setNeedsLayout, updateBoundsMethods declared in class javafx.scene.Node
accessibleHelpProperty, accessibleRoleDescriptionProperty, accessibleRoleProperty, accessibleTextProperty, addEventFilter, addEventHandler, applyCss, autosize, blendModeProperty, boundsInLocalProperty, boundsInParentProperty, buildEventDispatchChain, cacheHintProperty, cacheProperty, clipProperty, computeAreaInScreen, contains, contains, cursorProperty, depthTestProperty, disabledProperty, disableProperty, effectiveNodeOrientationProperty, effectProperty, eventDispatcherProperty, executeAccessibleAction, fireEvent, focusedProperty, focusTraversableProperty, focusVisibleProperty, focusWithinProperty, getAccessibleHelp, getAccessibleRole, getAccessibleRoleDescription, getAccessibleText, getBlendMode, getBoundsInLocal, getBoundsInParent, getCacheHint, getClip, getContentBias, getCursor, getDepthTest, getEffect, getEffectiveNodeOrientation, getEventDispatcher, getId, getInitialCursor, getInputMethodRequests, getLayoutBounds, getLayoutX, getLayoutY, getLocalToParentTransform, getLocalToSceneTransform, getNodeOrientation, getOnContextMenuRequested, getOnDragDetected, getOnDragDone, getOnDragDropped, getOnDragEntered, getOnDragExited, getOnDragOver, getOnInputMethodTextChanged, getOnKeyPressed, getOnKeyReleased, getOnKeyTyped, getOnMouseClicked, getOnMouseDragEntered, getOnMouseDragExited, getOnMouseDragged, getOnMouseDragOver, getOnMouseDragReleased, getOnMouseEntered, getOnMouseExited, getOnMouseMoved, getOnMousePressed, getOnMouseReleased, getOnRotate, getOnRotationFinished, getOnRotationStarted, getOnScroll, getOnScrollFinished, getOnScrollStarted, getOnSwipeDown, getOnSwipeLeft, getOnSwipeRight, getOnSwipeUp, getOnTouchMoved, getOnTouchPressed, getOnTouchReleased, getOnTouchStationary, getOnZoom, getOnZoomFinished, getOnZoomStarted, getOpacity, getParent, getProperties, getPseudoClassStates, getRotate, getRotationAxis, getScaleX, getScaleY, getScaleZ, getScene, getStyle, getStyleableParent, getStyleClass, getTransforms, getTranslateX, getTranslateY, getTranslateZ, getTypeSelector, getUserData, getViewOrder, hasProperties, hoverProperty, idProperty, inputMethodRequestsProperty, intersects, intersects, isCache, isDisable, isDisabled, isFocused, isFocusTraversable, isFocusVisible, isFocusWithin, isHover, isManaged, isMouseTransparent, isPickOnBounds, isPressed, isVisible, layoutBoundsProperty, layoutXProperty, layoutYProperty, localToParent, localToParent, localToParent, localToParent, localToParent, localToParentTransformProperty, localToScene, localToScene, localToScene, localToScene, localToScene, localToScene, localToScene, localToScene, localToScene, localToScene, localToSceneTransformProperty, localToScreen, localToScreen, localToScreen, localToScreen, localToScreen, lookup, lookupAll, managedProperty, mouseTransparentProperty, nodeOrientationProperty, notifyAccessibleAttributeChanged, onContextMenuRequestedProperty, onDragDetectedProperty, onDragDoneProperty, onDragDroppedProperty, onDragEnteredProperty, onDragExitedProperty, onDragOverProperty, onInputMethodTextChangedProperty, onKeyPressedProperty, onKeyReleasedProperty, onKeyTypedProperty, onMouseClickedProperty, onMouseDragEnteredProperty, onMouseDragExitedProperty, onMouseDraggedProperty, onMouseDragOverProperty, onMouseDragReleasedProperty, onMouseEnteredProperty, onMouseExitedProperty, onMouseMovedProperty, onMousePressedProperty, onMouseReleasedProperty, onRotateProperty, onRotationFinishedProperty, onRotationStartedProperty, onScrollFinishedProperty, onScrollProperty, onScrollStartedProperty, onSwipeDownProperty, onSwipeLeftProperty, onSwipeRightProperty, onSwipeUpProperty, onTouchMovedProperty, onTouchPressedProperty, onTouchReleasedProperty, onTouchStationaryProperty, onZoomFinishedProperty, onZoomProperty, onZoomStartedProperty, opacityProperty, parentProperty, parentToLocal, parentToLocal, parentToLocal, parentToLocal, parentToLocal, pickOnBoundsProperty, pressedProperty, pseudoClassStateChanged, queryAccessibleAttribute, relocate, removeEventFilter, removeEventHandler, requestFocus, resizeRelocate, rotateProperty, rotationAxisProperty, scaleXProperty, scaleYProperty, scaleZProperty, sceneProperty, sceneToLocal, sceneToLocal, sceneToLocal, sceneToLocal, sceneToLocal, sceneToLocal, sceneToLocal, sceneToLocal, screenToLocal, screenToLocal, screenToLocal, setAccessibleHelp, setAccessibleRole, setAccessibleRoleDescription, setAccessibleText, setBlendMode, setCache, setCacheHint, setClip, setCursor, setDepthTest, setDisable, setDisabled, setEffect, setEventDispatcher, setEventHandler, setFocused, setFocusTraversable, setHover, setId, setInputMethodRequests, setLayoutX, setLayoutY, setManaged, setMouseTransparent, setNodeOrientation, setOnContextMenuRequested, setOnDragDetected, setOnDragDone, setOnDragDropped, setOnDragEntered, setOnDragExited, setOnDragOver, setOnInputMethodTextChanged, setOnKeyPressed, setOnKeyReleased, setOnKeyTyped, setOnMouseClicked, setOnMouseDragEntered, setOnMouseDragExited, setOnMouseDragged, setOnMouseDragOver, setOnMouseDragReleased, setOnMouseEntered, setOnMouseExited, setOnMouseMoved, setOnMousePressed, setOnMouseReleased, setOnRotate, setOnRotationFinished, setOnRotationStarted, setOnScroll, setOnScrollFinished, setOnScrollStarted, setOnSwipeDown, setOnSwipeLeft, setOnSwipeRight, setOnSwipeUp, setOnTouchMoved, setOnTouchPressed, setOnTouchReleased, setOnTouchStationary, setOnZoom, setOnZoomFinished, setOnZoomStarted, setOpacity, setPickOnBounds, setPressed, setRotate, setRotationAxis, setScaleX, setScaleY, setScaleZ, setStyle, setTranslateX, setTranslateY, setTranslateZ, setUserData, setViewOrder, setVisible, snapshot, snapshot, startDragAndDrop, startFullDrag, styleProperty, toBack, toFront, toString, translateXProperty, translateYProperty, translateZProperty, usesMirroring, viewOrderProperty, visiblePropertyMethods declared in class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods declared in interface javafx.css.Styleable
getStyleableNode
-
Property Details
-
items
The underlying data model for the ListView. Note that it has a generic type that must match the type of the ListView itself. -
placeholder
TheNodeto show to the user when theListViewhas no content to show. This happens when the list model has no data or when a filter has been applied to the list model, resulting in there being nothing to show the user.- Since:
- JavaFX 8.0
- See Also:
-
selectionModel
The 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. Note that it has a generic type that must match the type of the ListView itself. -
focusModel
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. -
orientation
The orientation of theListView- this can either be horizontal or vertical. -
cellFactory
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
Cellclass documentation for more detail. -
fixedCellSize
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:
-
editable
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. -
editingIndex
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:
-
onEditStart
This event handler will be fired when the user successfully initiates editing. -
onEditCommit
This property is used when the user performs an action that should result in their editing input being persisted.
The EventHandler in this property should not be called directly - instead call
Cell.commitEdit(java.lang.Object)from within your custom ListCell. This will handle firing this event, updating the view, and switching out of the editing state. -
onEditCancel
This event handler will be fired when the user cancels editing a cell. -
onScrollTo
Called when there's a request to scroll an index into view usingscrollTo(int)orscrollTo(Object)- Since:
- JavaFX 8.0
- See Also:
-
-
Constructor Details
-
ListView
public ListView()Creates a default ListView which will display contents stacked vertically. As noObservableListis provided in this constructor, an empty ObservableList is created, meaning that it is legal to directly callgetItems()if so desired. However, as noted elsewhere, this is not the recommended approach (instead callsetItems(javafx.collections.ObservableList)).Refer to the
ListViewclass documentation for details on the default state of other properties. -
ListView
Creates a default ListView which will stack the contents retrieved from the providedObservableListvertically.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
ListViewclass documentation for details on the default state of other properties.- Parameters:
items- the list of items
-
-
Method Details
-
editAnyEvent
An EventType that indicates some edit event has occurred. It is the parent type of all other edit events:editStartEvent(),editCommitEvent()andeditCancelEvent().- Type Parameters:
T- the type of the objects stored in this ListView- Returns:
- the event type
-
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
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
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
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
Returns anObservableListthat contains the items currently being shown to the user. This may be null ifsetItems(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
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
- See Also:
-
placeholderProperty
TheNodeto show to the user when theListViewhas no content to show. This happens when the list model has no data or when a filter has been applied to the list model, resulting in there being nothing to show the user.- Returns:
- the
placeholderproperty - Since:
- JavaFX 8.0
- See Also:
-
setPlaceholder
Sets the value of theplaceholderproperty.- Property description:
- The
Nodeto show to the user when theListViewhas no content to show. This happens when the list model has no data or when a filter has been applied to the list model, resulting in there being nothing to show the user. - Parameters:
value- the value for theplaceholderproperty- Since:
- JavaFX 8.0
- See Also:
-
getPlaceholder
Gets the value of theplaceholderproperty.- Property description:
- The
Nodeto show to the user when theListViewhas no content to show. This happens when the list model has no data or when a filter has been applied to the list model, resulting in there being nothing to show the user. - Returns:
- the value of the
placeholderproperty - Since:
- JavaFX 8.0
- See Also:
-
setSelectionModel
Sets theMultipleSelectionModelto be used in the ListView. Despite a ListView requiring a MultipleSelectionModel, it is possible to configure it to only allow single selection (seeMultipleSelectionModel.setSelectionMode(javafx.scene.control.SelectionMode)for more information).- Parameters:
value- the MultipleSelectionModel to be used in this ListView
-
getSelectionModel
Returns the currently installed selection model.- Returns:
- the currently installed selection model
-
selectionModelProperty
The 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. Note that it has a generic type that must match the type of the ListView itself.- Returns:
- the selectionModel property
- See Also:
-
setFocusModel
Sets theFocusModelto be used in the ListView.- Parameters:
value- the FocusModel to be used in the ListView
-
getFocusModel
Returns the currently installedFocusModel.- Returns:
- the currently installed FocusModel
-
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.- Returns:
- the FocusModel property
- See Also:
-
setOrientation
Sets the orientation of the ListView, which dictates whether it scrolls vertically or horizontally.- Parameters:
value- the orientation of the ListView
-
getOrientation
Returns the current orientation of the ListView, which dictates whether it scrolls vertically or horizontally.- Returns:
- the current orientation of the ListView
-
orientationProperty
The orientation of theListView- this can either be horizontal or vertical.- Returns:
- the orientation property of this ListView
- See Also:
-
setCellFactory
Sets a new cell factory to use in the ListView. This forces all oldListCell'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
Returns the current cell factory.- Returns:
- the current cell factory
-
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
Cellclass documentation for more detail.- Returns:
- the cell factory property
- See Also:
-
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
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.
- Returns:
- the fixed cell size property
- Since:
- JavaFX 8.0
- See Also:
-
setEditable
public final void setEditable(boolean value) Sets the value of theeditableproperty.- 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.
- Parameters:
value- the value for theeditableproperty- See Also:
-
isEditable
public final boolean isEditable()Gets the value of theeditableproperty.- 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.
- Returns:
- the value of the
editableproperty - See Also:
-
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.- Returns:
- the editable property
- See Also:
-
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
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).- Returns:
- the editing index property
- See Also:
-
setOnEditStart
Sets theEventHandlerthat 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
Returns theEventHandlerthat will be called when the user begins an edit.- Returns:
- the EventHandler that will be called when the user begins an edit
-
onEditStartProperty
This event handler will be fired when the user successfully initiates editing.- Returns:
- the onEditStart event handler property
- See Also:
-
setOnEditCommit
Sets theEventHandlerthat will be called when the user has completed their editing. This is called as part of theCell.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
Returns theEventHandlerthat will be called when the user commits an edit.- Returns:
- the EventHandler that will be called when the user commits an edit
-
onEditCommitProperty
This property is used when the user performs an action that should result in their editing input being persisted.
The EventHandler in this property should not be called directly - instead call
Cell.commitEdit(java.lang.Object)from within your custom ListCell. This will handle firing this event, updating the view, and switching out of the editing state.- Returns:
- the onEditCommit event handler property
- See Also:
-
setOnEditCancel
Sets theEventHandlerthat will be called when the user cancels an edit.- Parameters:
value- the EventHandler that will be called when the user cancels an edit
-
getOnEditCancel
Returns theEventHandlerthat will be called when the user cancels an edit.- Returns:
- the EventHandler that will be called when the user cancels an edit
-
onEditCancelProperty
This event handler will be fired when the user cancels editing a cell.- Returns:
- the onEditCancel event handler property
- See Also:
-
edit
public void edit(int itemIndex) Instructs the ListView to begin editing the item in the given index, if the ListView iseditable. Once this method is called, if the currentcellFactoryProperty()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
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
-
setOnScrollTo
Sets the value of theonScrollToproperty.- Property description:
- Called when there's a request to scroll an index into view using
scrollTo(int)orscrollTo(Object) - Parameters:
value- the value for theonScrollToproperty- Since:
- JavaFX 8.0
- See Also:
-
getOnScrollTo
Gets the value of theonScrollToproperty.- Property description:
- Called when there's a request to scroll an index into view using
scrollTo(int)orscrollTo(Object) - Returns:
- the value of the
onScrollToproperty - Since:
- JavaFX 8.0
- See Also:
-
onScrollToProperty
Called when there's a request to scroll an index into view usingscrollTo(int)orscrollTo(Object)- Returns:
- the
onScrollToproperty - Since:
- JavaFX 8.0
- See Also:
-
refresh
public void refresh()Callingrefresh()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
Gets theCssMetaDataassociated with this class, which may include theCssMetaDataof its superclasses.- Returns:
- the
CssMetaData - Since:
- JavaFX 8.0
-
getControlCssMetaData
Gets the unmodifiable list of the control's CSS-styleable properties.- Overrides:
getControlCssMetaDatain classControl- Returns:
- the unmodifiable list of the control's CSS-styleable properties
- Since:
- JavaFX 8.0
-