简体   繁体   English

可能为null时的Java setCellValueFactory lambda表达式

[英]Java setCellValueFactory lambda expression when null is possible

I have the following line of code to set up a column in JavaFX: 我有以下代码行可以在JavaFX中设置一列:

branchActionColumn.setCellValueFactory(cd -> cd.getValue().getAction().getTextProperty());

This typically works fine. 这通常可以正常工作。 However, sometimes getAction() returns null (and that can be normal behavior). 但是,有时getAction()返回null(这可能是正常行为)。 In that case I'd like to just display the empty string "". 在这种情况下,我只想显示空字符串“”。 How could I do that? 我该怎么办?

I've tried: 我试过了:

branchActionColumn.setCellValueFactory(cd -> (cd.getValue().getAction() == null) ? new SimpleStringProperty("") : cd.getValue().getAction().getTextProperty());

While this displays the initial value of the property in the TableView, any subsequent changes made to the property are not reflected in the TableView. 虽然这会在TableView中显示该属性的初始值,但对该属性所做的任何后续更改都不会反映在TableView中。 I believe this is because I am creating a new property inside the lambda expression. 我相信这是因为我正在lambda表达式内创建一个新属性。

If I go back to the line branchActionColumn.setCellValueFactory(cd -> cd.getValue().getAction().getTextProperty()); 如果我回到该行branchActionColumn.setCellValueFactory(cd -> cd.getValue().getAction().getTextProperty()); then the TableView responds appropriately whenever the property changes. 然后只要属性更改,TableView就会适当响应。 This is the behavior that I want. 这是我想要的行为。 I just also want it to handle the case when getAction() returns null. 我也只希望它处理getAction()返回null的情况。

Here is a similar question, but it's for C# and it's not related to a CellValueFactory: C#, in List<>.ConvertAll method using lambda expression, how to make a filter when the object is null? 这是一个类似的问题,但这是针对C#的,它与CellValueFactory没有关系: C#,在使用Lambda表达式的List <>。ConvertAll方法中,当对象为null时如何进行过滤?

Try to use optional 尝试使用可选

branchActionColumn.setCellValueFactory(cd -> 
    Optional.ofNullable(cd.getValue().getAction())
        .map(action -> action.getTextProperty())
        .orElseGet(() -> new SimpleStringProperty(""))
);

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

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