首頁 > Java > java教程 > 主體

如何在 JavaFX ListView 中顯示自訂物件屬性?

Mary-Kate Olsen
發布: 2024-10-25 00:25:02
原創
382 人瀏覽過

How Can I Display Custom Object Properties in a JavaFX ListView?

如何使用自訂物件在 JavaFX 中填充 ListView

挑戰在於使用自訂物件而不是字串填充 ListView。使用 Word 物件的 observableArrayList,其中每個 Word 都有一個 wordString 和定義,我們希望 ListView 顯示 wordString 而不是整個 Word 物件。

自訂解決方案

一種方法涉及使用單元工廠從每個單元的 Word 物件中擷取 wordString。以下是更新後的程式碼片段:

<code class="java">listViewOfWords.setCellFactory(param -> new ListCell<Word>() {
    @Override
    protected void updateItem(Word item, boolean empty) {
        super.updateItem(item, empty);

        if (empty || item == null || item.getWord() == null) {
            setText(null);
        } else {
            setText(item.getWord());
        }
    }
});</code>
登入後複製

最佳化實作

1.避免重寫toString 進行UI 表示

與其重寫toString 進行UI 表示,不如考慮使用單元工廠來提取適當的資料以進行UI 表示。這使 UI 表示邏輯與物件的文字表示分離。

2.使用圖形節點自訂單元

單元工廠允許更靈活的自訂,包括在單元中新增圖形節點。這是一個範例:

<code class="java">public static class WordListCell extends ListCell<Word> {
    private final Label title = new Label();
    private final Label detail = new Label();
    private final VBox layout = new VBox(title, detail);

    public WordListCell() {
        super();
        title.setStyle("-fx-font-size: 20px;");
    }

    @Override
    protected void updateItem(Word item, boolean empty) {
        super.updateItem(item, empty);

        setText(null);

        if (empty || item == null || item.getWord() == null) {
            title.setText(null);
            detail.setText(null);
            setGraphic(null);
        } else {
            title.setText(item.getWord());
            detail.setText(
                    item.getDefinition() != null
                            ? item.getDefinition()
                            : "Undefined"
            );
            setGraphic(layout);
        }
    }
}</code>
登入後複製

3.不可變物件和可觀察屬性

為了防止意外的物件修改,建議使用不可變Word物件或具有可觀察屬性的物件進行欄位更新。這允許 UI 響應屬性更改。

4.動態更新

底層可觀察清單項目的變更(例如新增、刪除)將自動觸發檢視中的更新。若要回應物件內的屬性更改,您需要在單元工廠中實作偵聽器邏輯或使用擷取器。提取器有助於通知可觀察屬性的變更。

提取器範例

<code class="java">ObservableList<Word> wordsList = FXCollections.observableArrayList(word ->
        new Observable[] {
                word.wordProperty(),
                word.definitionProperty()
        }
);</code>
登入後複製

以上是如何在 JavaFX ListView 中顯示自訂物件屬性?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!