Java Reference
In-Depth Information
primaryStage.setTitle("StackOverflow Table");
primaryStage.setScene(scene);
primaryStage.show();
}
Clearly, this example requires more code than the example showing a
ListView
. Setting up a table is slightly
more complex, due to the different columns that are involved. There is not much difference between setting the
contents of the
ListView
and setting the contents of the
TableView
. This is achieved doing
tableView.setItems(getObservableList());
where the
getObservableList()
method is the same implementation as in the previous example. Note that we could
also use the convenient constructor
TableView<Question> tableView = new TableView<>(getObservableList());
When using a
TableView
, we have to define a number of
TableColumns
. This is done in the following code snippet.
TableColumn<Question, String> dateColumn = new TableColumn<>("Date");
TableColumn<Question, String> ownerColumn = new TableColumn<>("Owner");
TableColumn<Question, String> questionColumn = new TableColumn<>("Question");
Using the
TableColumn
constructor, we create one
TableColumn
with title “Date,” one with title “Owner,” and
a third one titled “Question.” The
Generics <Question, String>
indicate that each entry in a row represents a
Question
, and the individual cells in the specified column are of type
String
.
Next, the instances of
TableColumn
that we created need to know what data they should render. This is done
using
CellFactories
, as shown in the following snippet.
dateColumn.setCellValueFactory((CellDataFeatures<Question, String> cdf) -> {
Question q = cdf.getValue();
return new SimpleStringProperty(getTimeStampString(q.getTimestamp()));
});
A detailed description of the
setCellValueFactory
method is beyond the scope of this chapter. The reader
is encouraged to have a look at the JavaDoc of the
TableView
and
TableColumn
classes while working with tables.
The JavaDoc explains that we have to specify a
Callback
class with a call method that returns an
ObservableValue
containing the content of the specific cell. Fortunately, we can use a lambda expression for this.
The question we are displaying in this row can be obtained via the
CellDataFeatures
instance that is
passed as the single parameter in this lambda expression. Because we want to show the timestamp, we return a
SimpleStringProperty
whose content is set to the timestamp of the specified
Question
.
The same technique has to be used for the other
TableColumns
(containing the owner and the question
contained within the applicable
Question
object).
Finally, we have to add the columns to the
TableView
:
tableView.getColumns().addAll(dateColumn, ownerColumn, questionColumn);
Running this example results in the visual output shown in Figure
11-7
.
Search WWH ::
Custom Search