Java Reference
In-Depth Information
This code is clearly shorter than the code in the previous sample. We actually replaced
dateColumn.setCellValueFactory((CellDataFeatures<Question, String> cdf) -> {
Question q = cdf.getValue();
return new SimpleStringProperty(getTimeStampString(q.getTimestamp()));
});
by
dateColumn.setCellValueFactory(new PropertyValueFactory<>("timestampString"));
The same holds for the ownerColumn and the questionColumn .
We are using instances of javafx.scene.control.cell.PropertyValueFactory<S,T>(String name) for
defining what specific data should be rendered in which cell.
The PropertyValueFactory searches for a JavaFX property with the specified name and returns the
ObservableValue of this property when called. In case no property with such a name can be found, the JavaDoc says
the following.
In this example, the “firstName” string is used as a reference to an assumed firstNameProperty()
method in the Person class type (which is the class type of the TableView items list). Additionally,
this method must return a Property instance. If a method meeting these requirements is found,
then the TableCell is populated with this ObservableValue. In addition, the TableView will
automatically add an observer to the returned value, such that any changes fired will be observed
by the TableView, resulting in the cell immediately updating.
If no method matching this pattern exists, there is fall-through support for attempting to call
get<property>() or is<property>() (that is, getFirstName() or is FirstName() in the example above).
If a method matching this pattern exists, the value returned from this method is wrapped in a
ReadOnlyObjectWrapper and returned to the TableCell. However, in this situation, this means that
the TableCell will not be able to observe the ObservableValue for changes (as is the case in the first
approach above).
From this, it is clear that JavaFX Properties are the preferred way for rendering information in a TableView . So far,
we used the POJO Question class with JavaBean getter and setter methods as the value object for being displayed in
both a ListView and a TableView .
Although the preceding example also works without using JavaFX Properties, as stated by the JavaDoc, we now
modify the Question class to use a JavaFX Property for the owner information. The timeStamp and the text fields could
have been modified to use JavaFX Properties as well, but the mixed example shows that the fall-through scenario
described in the JavaDoc really works. The modified Question class is shown in Listing 11-17.
Listing 11-17. Implementation of Question Class Using JavaFX Properties for the Author Field
package projavafx;
import java.text.SimpleDateFormat;
import java.util.Date;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
 
Search WWH ::




Custom Search