setCellValueFactory for dynamic number of column in javaFX

≯℡__Kan透↙ 提交于 2019-12-25 09:42:17

问题


I making a logging GUI and my main view is a TableView with columns name loaded from a config file.

String format="Type:Date:Message";
//OR
String format="A:Different:Number:Of:Column";

String[] tok = format.split(":");
logTable.getColumns().clear();
for (String s : tok) {
    TableColumn<LogLine, String> col = new TableColumn<LogLine, String>(s);
    logTable.getColumns().add(col);
}

This works as expected. (I see the corrects column headers in my app). Then I want to add a CellValueFactory for each column:

    ObservableList<TableColumn<LogLine, ?>> colList =logTable.getColumns();

    for (int i = 0; i < colList.size(); i++)
    {
        colList.get(i).setCellValueFactory(cellData -> cellData.getValue().getTokens()[i]);
        // ...
    }

This is not working because java complains about i not defined in the lambda function:

Caused by: java.lang.Error: Unresolved compilation problem: 
    Local variable i defined in an enclosing scope must be final or effectively final

Any ideas to do it ? It's maybe a bad way, i'm new to Java/JavaFX.

Many thanks !


回答1:


Just copy i to an effectively-final variable:

for (int i = 0; i < colList.size(); i++)
{
    int index = i ;
    colList.get(i).setCellValueFactory(cellData -> cellData.getValue().getTokens()[index]);
    // ...
}


来源:https://stackoverflow.com/questions/28731598/setcellvaluefactory-for-dynamic-number-of-column-in-javafx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!