首页  >  文章  >  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