I am trying to make a table with a TableView and fill it programmatically based on a list of User
objects. The User
has three variables, nameProperty
(String), rankProperty
(Enum called Rank), and netMeritsProperty
(int). These are all stored in SimpleStringProperty
objects. My problem is that the data will not appear in the actual table, as shown here:
Here is my code for the table. What am I not understanding?
TableColumn name = new TableColumn("Name"); name.setCellValueFactory(new PropertyValueFactory("nameProperty")); TableColumn rank = new TableColumn("Rank"); rank.setCellValueFactory(new PropertyValueFactory("rankProperty")); TableColumn netMerits = new TableColumn("Net Merits"); netMerits.setCellValueFactory(new PropertyValueFactory("netMeritsProperty")); userTable.getColumns().addAll(name, rank, netMerits);
The answer is about attention, which string content you give as parameter of PropertyValueFactory
, and which methods are implemented in your encapsulated data type.
Instantiation :
new PropertyValueFactory("name")
will lookup for :
User.nameProperty()
Using PropertyValueFactory is simple, but it's not foolproof.
Probably the single most troublesome thing to using PropertyValueFactory is that the argument you provide must match the name of your JavaFX Bean property according to a STRICT convention:
- You must not include the word "Property"
- The matching is case-sensitive, so that "FIRSTNAME" will not be recognized as "firstName"
The best way is to look at your JavaFX Bean definition block, and find your Property line. Take the name of the property, omit the part that is "property", and copy it exactly (in the same case) to the string that you pass to PropertyValueFactory.
For example, say you have this JavaFX Bean definition:
public final String getFirstName() { return this.m_firstname.get(); } public final void setFirstName(String v) { this.m_firstname.set(v); } public final StringProperty firstNameProperty() { return m_firstname; }
Look at the name of the property in the last line, "firstNameProperty". Omit "Property", and the resulting string is what you must use -exactly- as your String argument to PropertyValueFactory, eg. "firstName".
tcolMyTableCol.setCellValueFactory(new PropertyValueFactory("firstName"));