java JavaFx 动态设置 Tableview 单元格背景颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25601448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaFx Set Tableview Cell Background Color Dynamically
提问by gursahib.singh.sahni
I want to add color to the color cell of the rows dynamically when ADD button is clicked. I am not able to change the background color of the cell. Please see the image for reference. Am not able to achieve that with the help of code. Thanks for help in advance.
我想在单击添加按钮时动态地为行的颜色单元格添加颜色。我无法更改单元格的背景颜色。请参阅图像以供参考。我无法在代码的帮助下实现这一目标。提前感谢您的帮助。
Snippet adding values to table :
将值添加到表的代码段:
@FXML
private void addEntity() {
data.add(new Inventory(codeTemp.getText(), articleNameTemp.getText(), Integer.parseInt(amountTemp.getText()), dcTemp.isSelected() ? true:false, stTemp.isSelected()?true:false, Utilities.toRGBCode(colorTemp.getValue()), informationTemp.getText(), data.size()+1));
inventoryTable.setItems(data);
}
回答by gursahib.singh.sahni
Did with the help of a callback on the column.
在列回调的帮助下完成的。
Callback<TableColumn<Inventory, String>, TableCell<Inventory, String>> cellFactory =
new Callback<TableColumn<Inventory, String>, TableCell<Inventory, String>>() {
public TableCell call(TableColumn p) {
TableCell cell = new TableCell<Person, String>() {
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setText(empty ? null : getString());
setStyle("-fx-background-color:"+getString());
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
};
return cell;
}
};