How to use the PropertyValueFactory correctly?

25,416

Solution 1

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<User, String>("name")

will lookup for :

User.nameProperty()

Solution 2

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:

  1. You must not include the word "Property"
  2. 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"));
Share:
25,416
mattbdean
Author by

mattbdean

Updated on January 29, 2020

Comments

  • mattbdean
    mattbdean over 4 years

    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<User, String> name = new TableColumn<>("Name");
    name.setCellValueFactory(new PropertyValueFactory<User, String>("nameProperty"));
    
    TableColumn<User, String> rank = new TableColumn<>("Rank");
    rank.setCellValueFactory(new PropertyValueFactory<User, String>("rankProperty"));
    
    TableColumn<User, String> netMerits = new TableColumn<>("Net Merits");
    netMerits.setCellValueFactory(new PropertyValueFactory<User, String>("netMeritsProperty"));
    
    userTable.getColumns().addAll(name, rank, netMerits);
    
  • Asif Mushtaq
    Asif Mushtaq almost 8 years
    Alexander I read about this one somewhere But unable to find the link. Have you link from where you read this? because there was complete guide how the property works. If compiler found namePeropty() then it will call to this else it will call to getName();