首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在javafx中仅更改listview中第一个单元格的背景色?

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

Stack Overflow用户
提问于 2018-10-28 12:11:57
回答 1查看 494关注 0票数 -1

如何在JavaFX中只更改listview中第一个单元格的背景色?我只想更改listview中第一个单元格的背景色。有没有办法做到这一点。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-28 12:41:42

您需要在ListView上实现一个自定义的CellFactory。然后,我们可以确定该单元格是否属于您用来填充ListviewList中的第一项。如果是这样,则仅对该单元格应用不同的样式。

我不知道是否有一种方法可以确定ListView__的第一个单元,但我们肯定可以捕获List__中的第一个项目。

考虑下面的应用程序。我们有一个ListView,它只显示一个字符串列表。

我们在ListView上设置一个自定义CellFactory,如果item是填充ListViewList中的第一个,则设置单元格样式。

代码语言:javascript
复制
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进行匹配不是最好的方法。

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

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53028313

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档