[英]JavaFX Coloring TableCell
我需要你的幫助!
我有一個帶有行的表(名稱等等)。現在,我想在對象上放置一個特定的tableCells背景,在這一行上有一個特定的值。 但我只能讀它來讀取這個細胞的價值。 但我需要讀取Object(在我的代碼中稱為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小提琴: 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("");
}
}
}
};
});
編輯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("");
}
}
}
};
});
編輯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("");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.