简体   繁体   中英

SetPropertyValueFactory of a TableColumn JavaFX

Let's say I have a class called Employee.

Employee has a String name, int age, and a custom object Workstyle ethic. A Workstyle has a private String style.

In our GUI class, we create TableColumns:

TableColumn<Professional, String> nameColumn = new TableColumn<>("NAME");
nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
//
TableColumn<Employee, Integer> ageColumn = new TableColumn<>("AGE");
nameColumn.setCellValueFactory(new PropertyValueFactory<>("age"));
//

Now here's where I'm lost. I'm unable to do:

TableColumn<Employee, String> workstyleColumn = new TableColumn<>("WORKSTYLE");
workstyleColumn.setCellValueFactory(new PropertyValueFactory<>("ethic.getStyle()"));

There must be SOME way of having:

TableColumn<Object Being Looked At, Type being put onto the column> columnTitle = new TableColumn<>(
{
     // I want to put tons of code here which EVENTUALLY ends with a object of type "Type being put onto the column".
});

Thanks for the help!

You need

workstyleColumn.setCellValueFactory(cellData -> 
    new ReadOnlyStringWrapper(cellData.getValue().getEthic().getStyle()));

The cellValueFactory is a Callback<TableColumn.CellDataFeatures, ObservableValue> , ie a function taking a TableColumn.CellDataFeatures and returning an ObservableValue . CellDataFeatures.getValue() gives the value for the row, so cellData.getValue().getEthic().getStyle() gives the value you want. Finally you wrap it in a ReadOnlyStringWrapper to give an ObservableValue .

if your using PropertyValueFactory you need to write the method name without "()".

So you need an Method in Employee wich returns the style of the ethic:

class Employee{
      private Ethic ethic;
      .... 

    public String getEthicStyle(){
         return ethic != null ? ethic.getStyle : "";
   }

}

and the rest looks like this:

TableColumn<Employee, String> workstyleColumn = new TableColumn<>("WORKSTYLE");
workstyleColumn.setCellValueFactory(new PropertyValueFactory<>("ethicStyle"));

EDIT

@James_D answer isn't wrong but if you realy want to use PropertyValueFactory you have to write the extra Method in Employee

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM