如何在JavaFX中只更改listview中第一个单元格的背景色?我只想更改listview中第一个单元格的背景色。有没有办法做到这一点。
发布于 2018-10-28 12:41:42
您需要在ListView
上实现一个自定义的CellFactory
。然后,我们可以确定该单元格是否属于您用来填充Listview
的List
中的第一项。如果是这样,则仅对该单元格应用不同的样式。
我不知道是否有一种方法可以确定ListView
__的第一个单元,但我们肯定可以捕获List
__中的第一个项目。
考虑下面的应用程序。我们有一个ListView
,它只显示一个字符串列表。
我们在ListView
上设置一个自定义CellFactory
,如果item
是填充ListView
的List
中的第一个,则设置单元格样式。
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();
}
}
The Result
显然,您需要进行一些调整来匹配您的数据模型,而仅仅通过String
进行匹配不是最好的方法。
这不会阻止用户选择第一个项目,并且如果在构建场景后对列表进行排序,则可能无法按预期工作。
虽然这可能会直接回答您的问题,但为了确保用户获得良好的体验,还需要考虑其他一些事情。
https://stackoverflow.com/questions/53028313
复制相似问题