fxml设置背景,改变行的背景颜色(或只是颜色)(javafx)

本文介绍如何在JavaFX中使用FXML设置TableView的行背景颜色。通过判断表格中balance值小于零,将对应行背景设为红色。实现方法是通过TableColumn的setCellFactory方法,自定义TableCell并在updateItem方法中更新单元格样式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I've a TableView. I want to change background color of rows according to some condition. For instance, if balance (getBalance()) is less than zero - set background color of that row to red. Here is my setCellValueFactory:

tc_proj_number.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getId().toString()));

tc_proj_date.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getValueDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().toString()));

tc_proj_amount.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getBalance().setScale(2).toPlainString()));

tc_proj_comment.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getComment()));

解决方案

Use TableColumn#setCellFactory method.

Try the following code (not tested):

tc_proj_amount.setCellFactory(column -> {

return new TableCell() {

@Override

protected void updateItem(String item, boolean empty) {

super.updateItem(item, empty);

if (item == null || empty) {

setText(null);

} else {

setText(item);

// Style row where balance < 0 with a different color.

BigDecimal balance = new BigDecimal(item);

TableRow currentRow = getTableRow();

if (balance.compareTo(BigDecimal.valueOf(0)) <0){

currentRow.setStyle("-fx-background-color: red;");

}

else currentRow.setStyle("");

}

}

};

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值