我需要你的帮助!
我有一个表,其中包含行(名称等..)
现在,当位于该行的对象具有特定值时,我想为特定的 tableCells 背景着色。但我只能让它读取这个单元格的值。但我需要读取对象(在我的代码中称为TableListObject
)知道我需要用哪种颜色给单元格着色。但是这个「颜色值」在该行中不可见(没有列)。
这是我的代码:
for(TableColumn tc:tView.getColumns()) {
if(tc.getId().equals("text")) {
tc.setCellValueFactory(newPropertyValueFactory<TableListObject,String>("text"));
// here i need to check the Objects value and coloring that cell
}
}
这是一个 HTML Fiddle 来可视化我的问题:https://jsfiddle.net/02ho4p6e/ https://jsfiddle.net/02ho4p6e/
调用您想要的列的单元工厂并覆盖updateItem
方法。您需要检查它是否为空,如果不是,您可以进行对象检查,然后您可以设置单元格背景的颜色或您想要的任何其他样式。希望这可以帮助。
tc.setCellFactory(column -> {
return new TableCell<TableListObject, String>() {
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText(null);
setStyle("");
} else {
if (item.equals("Something")) {
setStyle("-fx-background-color: blue");
} else {
setStyle("");
}
}
}
};
});
EDIT 1:
如果您想使用同一行中另一个单元格的值。您必须使用该行的索引并获取检查所需的项目。
tc.setCellFactory(column - > {
return new TableCell < TableListObject, String > () {
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText(null);
setStyle("");
} else {
int rowIndex = getTableRow().getIndex();
String valueInSecondaryCell = getTableView().getItems().get(rowIndex).getMethod();
if (valueInSecondaryCell.equals("Something Else")) {
setStyle("-fx-background-color: yellow"); //Set the style in the first cell based on the value of the second cell
} else {
setStyle("");
}
}
}
};
});
EDIT 2:
根据建议改进了答案。这使用引用的对象。
else {
TableListObject listObject = (TableListObject) getTableRow().getItem();
if (listObject.getMethod().equals("Something Else")) {
setStyle("-fx-background-color: yellow"); //Set the style in the first cell based on the value of the second cell
} else {
setStyle("");
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)