亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在javafx中僅更改listview中第一個單元格的背景顏色?

如何在javafx中僅更改listview中第一個單元格的背景顏色?

喵喵時光機 2021-12-10 17:09:15
如何在 JavaFX 中僅更改列表視圖中第一個單元格的背景顏色?我只想更改列表視圖中第一個單元格的背景顏色。有沒有辦法做到這一點。
查看完整描述

1 回答

?
嚕嚕噠

TA貢獻1784條經驗 獲得超7個贊

您需要CellFactory在ListView. 然后我們可以確定該單元格是否屬于List您用來填充Listview. 如果是這樣,請僅對該單元格應用不同的樣式。


我不知道是否有一種方法來確定第一小區的ListView,但我們一定可以捕捉在第一項List。


考慮以下應用程序。我們有一個ListView只顯示字符串列表的。


我們設置自定義CellFactory的ListView,并設置單元格樣式,如果item是在第一List填充ListView。


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();

    }

}

結果

http://img1.sycdn.imooc.com//61b319540001cf7b02830298.jpg

顯然,您需要進行一些調整以匹配您的數據模型,并且僅通過 a 進行匹配String并不是最好的方法。

這不會阻止用戶選擇第一個項目,并且如果在構建場景后對列表進行排序,則可能無法按預期工作。

雖然這可能會回答您的直接問題,但為了確保為用戶提供良好的體驗,還需要考慮其他事項。


查看完整回答
反對 回復 2021-12-10
  • 1 回答
  • 0 關注
  • 628 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號