java设置tableitem颜色,JavaFX设置TableColumn的单元格背景色

TableColumn tc = new TableColumn();

tc.getStyleClass.add(".style in css file")

I set up the TableColumn with a CSS file, and I want to give each cell different background colors. How can I accomplish this?

Example) TableColumn 1~5

TableColumn 1, row 3 has black and

TableColumn 5, row 4 has green ... etc

解决方案

Create a cellFactory that selects the background color based on the column & row index.

Example:

TableView> tableView = new TableView<>();

// sample item class contains a single property with the same type as the type parameter (String in this case)

tableView.getItems().addAll(

new Item<>("1"),

new Item<>("2"),

new Item<>("4"),

new Item<>("5"),

new Item<>("6"),

new Item<>("7"),

new Item<>("8"),

new Item<>("9")

);

// create columns

TableColumn, String> column1 = new TableColumn<>("value");

TableColumn, Void> column2 = new TableColumn<>();

tableView.getColumns().addAll(column1, column2);

// create list of colors (CSS)

final List colors = Arrays.asList(

"blue",

"green",

"red",

"violet",

"yellow",

...

);

Callback factory = new Callback, Object>, TableCell, Object>>() {

private int columns = tableView.getColumns().size();

@Override

public TableCell, Object> call(TableColumn, Object> param) {

return new TableCell, Object>() {

private int columnIndex = param.getTableView().getColumns().indexOf(param);

@Override

public void updateIndex(int i) {

super.updateIndex(i);

// select color based on index of row/column

if (i >= 0) {

// select color repeating the color, if we run out of colors

String color = colors.get((i * columns + columnIndex) % colors.size());

this.setStyle("-fx-my-cell-background: " + color + ";");

System.out.println(getStyle());

}

}

@Override

protected void updateItem(Object item, boolean empty) {

super.updateItem(item, empty);

// assign item's toString value as text

if (empty || item == null) {

setText(null);

} else {

setText(item.toString());

}

}

};

}

};

column1.setCellValueFactory(new PropertyValueFactory<>("value"));

column1.setCellFactory(factory);

column2.setCellFactory(factory);

Scene scene = new Scene(tableView);

scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());

style.css

.table-cell:filled {

-fx-background-color: -fx-my-cell-background;

}

.table-view:row-selection .table-row-cell:selected .table-cell {

-fx-background-color: null;

}

.table-view:cell-selection .table-cell:selected {

-fx-background-color: -fx-table-cell-border-color, -fx-background;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值