首頁  >  文章  >  Java  >  如何在 JavaFX ListView 中顯示自訂物件?

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

Patricia Arquette
Patricia Arquette原創
2024-10-24 18:47:55380瀏覽

How to Display Custom Objects in a JavaFX ListView?

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

使用 JavaFX 時,使用自訂物件填充 ListView 所需的方法與使用字串略有不同。本文將為這個問題提供詳細的解決方案。

問題陳述

在JavaFX 中使用自訂物件的ObservableArrayList 時,ListView 將物件本身顯示為字串,而不是擷取並顯示物件所需的屬性(例如,Word 物件中的單字)。

解是在 ListView 中使用 Cell Factory。單元工廠可讓您自訂 ListView 中每個單元的呈現方式。

第 1 步:建立單元工廠

建立一個擴充 ListCell 的新類別。在本例中,我們將其命名為 WordCell。

public class WordCell extends 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());
        }
    }
}

第2 步:在ListView 中設定單元格工廠

將WordCell 類別指定為

ListView<Word> listViewOfWords = new ListView<>(wordsList);
listViewOfWords.setCellFactory(listViewOfWords.new WordCell());

範例應用程式範例應用程式範例應用程式

這是一個演示所描述方法的範例應用程式:

import javafx.application.Application;
import javafx.collections.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;

public class ListViewCustomObject extends Application {

    @Override
    public void start(Stage stage) {
        ObservableList<Word> wordsList = FXCollections.observableArrayList();
        wordsList.add(new Word("First Word", "Definition of First Word"));
        wordsList.add(new Word("Second Word", "Definition of Second Word"));
        wordsList.add(new Word("Third Word", "Definition of Third Word"));

        ListView<Word> listViewOfWords = new ListView<>(wordsList);
        listViewOfWords.setCellFactory(listViewOfWords.new WordCell());

        stage.setScene(new Scene(listViewOfWords));
        stage.show();
    }

    public static class Word {
        private final String word;
        private final String definition;

        public Word(String word, String definition) {
            this.word = word;
            this.definition = definition;
        }

        public String getWord() {
            return word;
        }

        public String getDefinition() {
            return definition;
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

透過執行以下步驟,您可以填充您的ListView使用自訂物件並在每個單元格中顯示所需的屬性。

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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn