如何在JavaFX中动态更改列表视图中项目的背景

我正在编写一个程序,它将一组项放在listview中。 然后它检查它是否在数据库中找到了项目。 如果在数据库中找不到该项,我想在listview中更改该项的背景。 我正在使用JavaFX来完成这个程序。

我该怎么做呢?

您可以使用ListView的自定义单元工厂来检查条件,并将适当的css样式类应用于每个项目/单元格。

以下代码显示了如何使用String类型的项目进行Listview。

listView.setCellFactory(new Callback, ListCell>(){ @Override public ListCell call(ListView p) { ListCell cell = new ListCell(){ @Override protected void updateItem(String t, boolean bln) { super.updateItem(t, bln); if (t != null ) { setText( t); if (item_is_not_available){ if (!getStyleClass().contains("mystyleclass") { getStyleClass().add("mystyleclass"); } } else { getStyleClass().remove("mystyleclass"); } } else { setText(""); } } }; return cell; } }); 

在你的css文件中, mystyleclass的可能定义可能如下所示(显示红色背景不可用的项目):

 .mystyleclass{ -fx-background-color: #ff0000; }