简体   繁体   English

TableColumn JavaFX的SetPropertyValueFactory

[英]SetPropertyValueFactory of a TableColumn JavaFX

Let's say I have a class called Employee. 假设我有一个名为Employee的类。

Employee has a String name, int age, and a custom object Workstyle ethic. Employee具有字符串名称,整数年龄和自定义对象Workstyle道德。 A Workstyle has a private String style. 工作样式具有专用的字符串样式。

In our GUI class, we create TableColumns: 在GUI类中,我们创建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 . cellValueFactoryCallback<TableColumn.CellDataFeatures, ObservableValue> ,即采用TableColumn.CellDataFeatures并返回ObservableValue的函数。 CellDataFeatures.getValue() gives the value for the row, so cellData.getValue().getEthic().getStyle() gives the value you want. CellDataFeatures.getValue()提供该行的值,因此cellData.getValue().getEthic().getStyle()提供您想要的值。 Finally you wrap it in a ReadOnlyStringWrapper to give an ObservableValue . 最后,将其包装在ReadOnlyStringWrapper以提供ObservableValue

if your using PropertyValueFactory you need to write the method name without "()". 如果您使用PropertyValueFactory,则需要编写不带“()”的方法名。

So you need an Method in Employee wich returns the style of the ethic: 因此,您需要在Employee方法中返回道德风格:

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 @James_D答案没有错,但是如果您确实要使用PropertyValueFactory,则必须在Employee中编写额外的Method

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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