2016-11-20 20 views
0

你好,我試圖創建表視圖,動態欄 我想在第一列中添加,除了第一個所有頁眉和其他細胞可以是0值表視圖如何定義setCellValueFactory

這是給我一個錯誤「java.lang.IndexOutOfBoundsException:指數:2,大小:2

我真的不知道如何definie setCellValueFactory

用戶添加列表對象,該列表設置在列標題中。

for(Object c : objectList){ 
    TableColumn<List<String>, String> table1 = new TableColumn<>(); 
    table1.setText(c.getName()); 
    table1.setCellValueFactory(data -> { 
     List<String> rowValues = data.getValue(); 
     String cellValue= rowValues.get(objectList.indexOf(c)); 
     return new ReadOnlyStringWrapper(cellValue); 
    }); 

現在我想添加行表例如

我有表頭

|Row|Object1|Object2| 

,所以我想我的表看起來像

|Row|Object1|Object2| 

|Object1|0 |0  | 

|Object2|0 |0  | 




ObservableList<String> datal = FXCollections.observableArrayList(); 
    for(Object a: objectList){ 
     datal.clear(); 
      int index = objectList.indexOf(a); 
     if(index > 0){ 
      datal.add(a.getName()); 
     }else{ 
      datal.add(objectList.get(index+ 1).getName()); 
     } 

     for(int i = index+ 1; i <objectList.size() ;i++){ 
      datal.add("0"); 
     } 
     tableview.getItems().add(datal); 

但是,當我數據1 .clear()我得到錯誤java.lang.IndexOutOfBoundsException:索引:1,大小:1,當我不使用這個函數所有行看起來這個s AME

編輯

這看起來不錯,但我需要另一套零的表

|物體| Object1 |對象2 | Object3 |

| Object1 | null | 0 | 0 |

| Object2 | null | null | 0 |

| Object3 | null | null | null |

+1

燦你給我們一個我們可以運行自己的實例嗎?即完整的代碼,table1,objectList,data1的定義......這也不是很清楚你在這裏問什麼。 –

+0

與第二個代碼塊相關的第一個代碼塊在哪裏? 'c'在同一範圍內?如何將值(列表)添加到表中? 請提供[最小,完全和可驗證示例](http://stackoverflow.com/help/mcve) – Itai

+0

第一碼塊與第二塊CDE –

回答

1

您將一次又一次地添加相同的列表作爲項目。也許你打算在循環中創建新的列表:

for(Object a: objectList){ 
    ObservableList<String> datal = FXCollections.observableArrayList(); 
    // datal.clear(); 
    ... 
} 

而且你認爲至少有objectList.size()項目在每一個名單,這將不會是這樣,除非objectList項目的所有元素都等於第一一。

因此,你需要因此,你需要檢查item列表的大小在cellValueFactory

table1.setCellValueFactory(data -> { 
    List<String> rowValues = data.getValue(); 
    int index = objectList.indexOf(c); 
    return index >= 0 && index < rowValues.size() 
       ? new SimpleStringProperty(rowValues.get(index)) // does just the same as ReadOnlyStringWrapper in this case 
       : null; // no value, if outside of valid index range 
}); 

否則,你會得到那些IndexOutOfBoundsException S表示某些行...

+0

謝謝相同的方法,但還有一個問題我不能t在遊戲表中設置零,我在之前的文章中介紹過 –

相關問題