您好我尝试使用动态列创建表视图 我想在第一列中添加除第一列之外的所有标题,另一个单元格可以是0值
它给了我一个错误" java.lang.IndexOutOfBoundsException:Index:2,Size:2
我真的不明白如何定义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);
但是当我datal.clear()我得到错误java.lang.IndexOutOfBoundsException:索引:1,大小:1,当我不使用此函数时,所有行看起来都一样
被修改
它看起来不错,但我需要在表格中另外设置一组零
|物体| Object1 | Object2的| Object3 |
| Object1 |空| 0 | 0 |
| Object2的|空|空| 0 |
| Object3 |空|空|空|
答案 0 :(得分: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
个...