The TableView control is designed to visualize an unlimited number of rows
of data, broken out into columns. A TableView is therefore very similar to the
ListView
control, with the addition of support for columns. For an
example on how to create a TableView, refer to the 'Creating a TableView'
control section below.
The TableView control has a number of features, including:
TableColumn
API:
cell factories
to
easily customize cell
contents in both rendering and editing
states.
minWidth
/
prefWidth
/
maxWidth
,
and also fixed width columns
.
column nesting
resizing policies
to
dictate what happens when the user resizes columns.
multiple column sorting
by clicking
the column header (hold down Shift keyboard key whilst clicking on a
header to sort by multiple columns).
Note that TableView is intended to be used to visualize data - it is not
intended to be used for laying out your user interface. If you want to lay
your user interface out in a grid-like fashion, consider the
javafx.scene.layout.GridPane
layout instead.
Creating a TableView is a multi-step process, and also depends on the
underlying data model needing to be represented. For this example we'll use
an ObservableList<Person>, as it is the simplest way of showing data in a
TableView. The Person
class will consist of a first
name and last name properties. That is:
public class Person {
private StringProperty firstName;
public void setFirstName(String value) { firstNameProperty().set(value);
public String getFirstName() { return firstNameProperty().get(); }
public StringProperty firstNameProperty() {
if (firstName == null) firstName = new SimpleStringProperty(this, "firstName");
return firstName;
}
private StringProperty lastName;
public void setLastName(String value) { lastNameProperty().set(value); }
public String getLastName() { return lastNameProperty().get(); }
public StringProperty lastNameProperty() {
if (lastName == null) lastName = new SimpleStringProperty(this, "lastName");
return lastName;
}
}}
Firstly, a TableView instance needs to be defined, as such:
TableView<Person> table = new TableView<>();
With the basic table defined, we next focus on the data model. As mentioned, for this example, we'll be using an ObservableList<Person>. We can immediately set such a list directly in to the TableView, as such:
ObservableList<Person> teamMembers = getTeamMembers();
table.setItems(teamMembers);
With the items set as such, TableView will automatically update whenever
the teamMembers
list changes. If the items list is available
before the TableView is instantiated, it is possible to pass it directly into
the constructor.
At this point we now have a TableView hooked up to observe the
teamMembers
observableList. The missing ingredient
now is the means of splitting out the data contained within the model and
representing it in one or more TableColumn
instances. To
create a two-column TableView to show the firstName and lastName properties,
we extend the last code sample as follows:
ObservableList<Person> teamMembers = ...;
table.setItems(teamMembers);
TableColumn<Person,String> firstNameCol = new TableColumn<>("First Name");
firstNameCol.setCellValueFactory(new PropertyValueFactory<>("firstName"));
TableColumn<Person,String> lastNameCol = new TableColumn<>("Last Name");
lastNameCol.setCellValueFactory(new PropertyValueFactory<>("lastName"));
table.getColumns().setAll(firstNameCol, lastNameCol);
With the code shown above we have fully defined the minimum properties required to create a TableView instance. Running this code (assuming the people ObservableList is appropriately created) will result in a TableView being shown with two columns for firstName and lastName. Any other properties of the Person class will not be shown, as no TableColumns are defined.
The code shown above is the shortest possible code for creating a TableView
when the domain objects are designed with JavaFX properties in mind
(additionally, javafx.scene.control.cell.PropertyValueFactory
supports
normal JavaBean properties too, although there is a caveat to this, so refer
to the class documentation for more information). When this is not the case,
it is necessary to provide a custom cell value factory. More information
about cell value factories can be found in the TableColumn
API
documentation, but briefly, here is how a TableColumn could be specified:
firstNameCol.setCellValueFactory(new Callback<CellDataFeatures<Person, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<Person, String> p) {
// p.getValue() returns the Person instance for a particular TableView row
return p.getValue().firstNameProperty();
});
// or with a lambda expression:
firstNameCol.setCellValueFactory(p -> p.getValue().firstNameProperty());
}
To track selection and focus, it is necessary to become familiar with the
SelectionModel
and FocusModel
classes. A TableView 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 TableView 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 TableView instance, it is therefore necessary
to do the following:
tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
The visuals of the TableView can be entirely customized by replacing the
default row factory
. A row factory is used to
generate TableRow
instances, which are used to represent an entire
row in the TableView.
In many cases, this is not what is desired however, as it is more commonly
the case that cells be customized on a per-column basis, not a per-row basis.
It is therefore important to note that a TableRow
is not a
TableCell
. A TableRow
is simply a container for zero or more
TableCell
, and in most circumstances it is more likely that you'll
want to create custom TableCells, rather than TableRows. The primary use case
for creating custom TableRow instances would most probably be to introduce
some form of column spanning support.
You can create custom TableCell
instances per column by assigning
the appropriate function to the TableColumn
cell factory
property.
See the Cell
class documentation for a more complete
description of how to write custom Cells.
Prior to JavaFX 8.0, the TableView control would treat the
items
list as the view model, meaning that any changes to
the list would be immediately reflected visually. TableView would also modify
the order of this list directly when a user initiated a sort. This meant that
(again, prior to JavaFX 8.0) it was not possible to have the TableView return
to an unsorted state (after iterating through ascending and descending
orders).
Starting with JavaFX 8.0 (and the introduction of SortedList
), it
is now possible to have the collection return to the unsorted state when
there are no columns as part of the TableView
sort order
. To do this, you must create a SortedList
instance, and bind its
comparator
property to the TableView comparator
property,
list so:
// create a SortedList based on the provided ObservableList
SortedList sortedList = new SortedList(FXCollections.observableArrayList(2, 1, 3));
// create a TableView with the sorted list set as the items it will show
final TableView<Integer> tableView = new TableView<>(sortedList);
// bind the sortedList comparator to the TableView comparator
sortedList.comparatorProperty().bind(tableView.comparatorProperty());
// Don't forget to define columns!
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 TableView, it is highly
recommended that editing be
per-TableColumn
,
rather than per row
, as more often than not
you want users to edit each column value differently, and this approach allows
for editors specific to each column. It is your choice whether the cell is
permanently in an editing state (e.g. this is common for CheckBox
cells),
or to switch to a different UI when editing begins (e.g. when a double-click
is received on a cell).
To know when editing has been requested on a cell,
simply override the javafx.scene.control.Cell.startEdit()
method, and
update the cell text
and
graphic
properties as
appropriate (e.g. set the text to null and set the graphic to be a
TextField
). Additionally, you should also override
Cell.cancelEdit()
to reset the UI back to its original visual state
when the editing concludes. In both cases it is important that you also
ensure that you call the super method to have the cell perform all duties it
must do to enter or exit its editing mode.
Once your cell is in an editing state, the next thing you are most probably
interested in is how to commit or cancel the editing that is taking place. This is your
responsibility as the cell factory provider. Your cell implementation will know
when the editing is over, based on the user input (e.g. when the user presses
the Enter or ESC keys on their keyboard). When this happens, it is your
responsibility to call Cell.commitEdit(Object)
or
Cell.cancelEdit()
, as appropriate.
When you call Cell.commitEdit(Object)
an event is fired to the
TableView, which you can observe by adding an EventHandler
via
TableColumn.setOnEditCommit(javafx.event.EventHandler)
. Similarly,
you can also observe edit events for
edit start
and edit cancel
.
By default the TableColumn 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
CellEditEvent
that is
fired. It is simply a matter of calling
javafx.scene.control.TableColumn.CellEditEvent.getNewValue()
to
retrieve this value.
It is very important to note that if you call
TableColumn.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
TableColumn.addEventHandler(javafx.event.EventType, javafx.event.EventHandler)
method to add a TableColumn.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.
extends
<S> | The type of the objects contained within the TableView items list. |
TableColumn, TablePosition