A TableView
is made up of a number of TableColumn instances. Each
TableColumn in a table is responsible for displaying (and editing) the contents
of that column. As well as being responsible for displaying and editing data
for a single column, a TableColumn also contains the necessary properties to:
minWidth
/prefWidth
/maxWidth
and width
properties)
visibility
toggled
header text
nested columns
it may contain
context menu
when the user
right-clicks the column header area
comparator
, sortable
and
sortType
)
text
(what to show in the column
header area), and the column cell value factory
(which is used to populate individual cells in the column). This can be
achieved using some variation on the following code:
ObservableList<Person> data = ...
TableView<Person> tableView = new TableView<Person>(data);
TableColumn<Person,String> firstNameCol = new TableColumn<Person,String>("First Name");
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();
});
}
tableView.getColumns().add(firstNameCol);}
This approach assumes that the object returned from p.getValue()
has a JavaFX ObservableValue
that can simply be returned. The benefit of this
is that the TableView will internally create bindings to ensure that,
should the returned ObservableValue
change, the cell contents will be
automatically refreshed.
In situations where a TableColumn must interact with classes created before
JavaFX, or that generally do not wish to use JavaFX apis for properties, it is
possible to wrap the returned value in a ReadOnlyObjectWrapper
instance. For
example:
firstNameCol.setCellValueFactory(new Callback<CellDataFeatures<Person, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<Person, String> p) {
return new ReadOnlyObjectWrapper(p.getValue().getFirstName());
});}
It is hoped that over time there will be convenience cell value factories
developed and made available to developers. As of the JavaFX 2.0 release,
there is one such convenience class: PropertyValueFactory
. This class
removes the need to write the code above, instead relying on reflection to
look up a given property from a String. Refer to the
PropertyValueFactory
class documentation for more information
on how to use this with a TableColumn.
Finally, for more detail on how to use TableColumn, there is further documentation in
the TableView
class documentation.
extends
<S> | The type of the TableView generic type (i.e. S == TableView<S>) | |
<T> | The type of the content in all cells in this TableColumn. |
TableView, TableCell, TablePosition