Cell factory in javafx

前端 未结 2 830
别跟我提以往
别跟我提以往 2020-12-08 23:14

I am using JavaFx 2.0 and Java 7. The question is regarding Table View in JavaFX.

The below sample code creates a firstName column and assigns cell factory and cell

相关标签:
2条回答
  • 2020-12-09 00:03

    Straightforwardly,

    Cell Value Factory : it is like a "toString()" of only part of the row item for that related cell.
    Cell Factory : it is a renderer of the cell from the cell item. Default behavior is setText(cell.item.toString()) if the cell item is not a Node, setGraphic((Node)cell.item) otherwise. Set this property if the cell is supposed to support editing OR if you want more graphics (controls) other than default Label.

    So for your scenario, leaving cell factory with default value will be sufficient (2). And here is sample code for (1):

    firstAndLastNameCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Person, String>, ObservableValue<String>>() {
    
        @Override
        public ObservableValue<String> call(TableColumn.CellDataFeatures<Person, String> p) {
            if (p.getValue() != null) {
                return new SimpleStringProperty(p.getValue().getPrefix() + " " + p.getValue().getFirstName() + "," + p.getValue().getLastName());
            } else {
                return new SimpleStringProperty("<no name>");
            }
        }
    });
    
    0 讨论(0)
  • 2020-12-09 00:03

    You can also just modify the getter method of your data object. In your case this is the class Person, which holds firstName, lastName and (presumably) prefix.

    Add a new method to the Person class:

    public String getTotalName() {
      return this.prefix + " " + this.getLastName() + ", " + this.getFirstName();
    }
    

    and then just apply the CellValueFactory:

    totalNameCol.setCellValueFactory(
      new PropertyValueFactory<Person,String>("totalName")
    );
    

    I find this more comfortable and than using callbacks.

    0 讨论(0)
提交回复
热议问题