如何更改javafx中listview中仅第一个单元格的背景颜色?

时间:2018-10-28 04:11:57

标签: java listview javafx

如何在JavaFX中仅更改列表视图中第一个单元格的背景颜色?我只想更改列表视图中第一个单元格的背景颜色。有什么办法可以做到这一点。

1 个答案:

答案 0 :(得分:3)

您需要在CellFactory上实现自定义ListView。然后,我们可以确定该单元格是否属于您用来填充List的{​​{1}}中的第一项。如果是这样,请仅对该单元格应用另一种样式。

我不知道是否可以确定Listview的第一个单元格,但是我们可以肯定地捕获ListView中的第一个项目

请考虑以下应用程序。我们有一个List仅显示字符串列表。

如果ListView是填充CellFactory的{​​{1}}中的第一个ListView,则在item上设置自定义List并设置单元格样式。 / p>


ListView
  

结果

screenshot


很显然,您需要进行一些调整以匹配您的数据模型,而仅通过import javafx.application.Application; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class Main extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { // Simple interface VBox root = new VBox(5); root.setPadding(new Insets(10)); root.setAlignment(Pos.CENTER); // Create the ListView ListView<String> listView = new ListView<>(); listView.getItems().setAll("Title", "One", "Two", "Three", "Four", "Five"); // Set the CellFactory for the ListView listView.setCellFactory(list -> { ListCell<String> cell = new ListCell<String>() { @Override protected void updateItem(String item, boolean empty) { super.updateItem(item, empty); if (empty || item == null) { // There is no item to display in this cell, so leave it empty setGraphic(null); // Clear the style from the cell setStyle(null); } else { // If the item is equal to the first item in the list, set the style if (item.equalsIgnoreCase(list.getItems().get(0))) { // Set the background color to blue setStyle("-fx-background-color: blue; -fx-text-fill: white"); } // Finally, show the item text in the cell setText(item); } } }; return cell; }); root.getChildren().add(listView); // Show the Stage primaryStage.setScene(new Scene(root)); primaryStage.show(); } } 进行匹配并不是最佳方法。

这不会阻止用户选择第一项,并且如果在构建场景后对列表进行了排序,则可能无法按预期工作。

虽然这可能回答您的直接问题,但为了确保用户的良好体验,还需要考虑其他事项。

相关问题