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

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

JavaFX ListCell updateItem 執行兩次?

JavaFX ListCell updateItem 執行兩次?

九州編程 2023-03-23 16:16:26
我正在嘗試在 ListView 中創建自定義單元格,但每次我添加一個新項目時, updateItem (TextFlow item, Boolean empty)都會執行兩次:一次它收到 null和true,第二次它沒有(!空和假)如果我不實施setCellFactory方法,那么我可以毫無問題地將項目添加到表中。沒有自定義 cellFactory 的ListView但是,當我實施它時,它只是創建了 10 個空單元格(內容在哪里?)。帶有自定義 cellFactory 的ListViewpublic class Controller implements Initializable {@FXMLprivate ListView <TextFlow> console;private ObservableList<TextFlow> data = FXCollections.observableArrayList();public void initialize(URL location, ResourceBundle resources) {    console.setCellFactory(new Callback<ListView<TextFlow>, ListCell<TextFlow>>() {        @Override        public ListCell<TextFlow> call(ListView<TextFlow> param) {            return new ListCell<TextFlow>() {                @Override                protected void updateItem(TextFlow item, boolean empty) {                    super.updateItem(item, empty);                    if (item != null) {                        setItem(item);                        setStyle("-fx-control-inner-background: blue;");                    } else {                        System.out.println("Item is null.");                    }                }            };        }    });    for (int i = 0 ; i < 10; i++) {        Text txt = getStyledText("This is item number " + i + ".");        TextFlow textFlow = new TextFlow();        textFlow.getChildren().add(txt);        data.add(textFlow);    }    console.setItems(data);}private Text getStyledText (String inputText) {    Text text = new Text(inputText);    text.setFont(new Font("Courier New",12));    text.setFill(Paint.valueOf("#000000"));    return text;}}
查看完整描述

1 回答

?
白板的微信

TA貢獻1883條經驗 獲得超3個贊

updateItem可以調用任意次數,可以傳遞不同的項目,單元格可以從空變為非空,反之亦然。ListView創建與您在屏幕上看到的一樣多的單元格,并用項目填充它們。例如,滾動或修改列表items或調整大小ListView可以導致更新。


出于這個原因,任何單元格都需要能夠處理傳遞null給該方法的任意項目序列(或+空)updateItem。


此外,您應該避免調用setItem自己,因為super.updateItem已經這樣做了。setGraphic如果要在單元格中顯示項目,請改用:


@Override

public ListCell<TextFlow> call(ListView<TextFlow> param) {

    return new ListCell<TextFlow>() {

        @Override

        protected void updateItem(TextFlow item, boolean empty) {

            super.updateItem(item, empty);


            if (item != null) {

                setStyle("-fx-control-inner-background: blue;");

                setGraphic(item);

            } else {

                setStyle(null);

                setGraphic(null);

                System.out.println("Item is null.");

            }


        }

    };

}


查看完整回答
反對 回復 2023-03-23
  • 1 回答
  • 0 關注
  • 105 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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