将TableView列连接到HashMap值 [英] Connect TableView columns to the HashMap values

查看:225
本文介绍了将TableView列连接到HashMap值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个简单的crud-redactor,并且我遇到了一个问题:

I'm writing a simple crud-redactor, and there is a problem I stuck on:

我有一个课程:

public class Note {
    List<String> columnNames;
    HashMap<String, SimpleStringProperty> items;
}

我需要以某种方式连接 TableView 通过 setCellValueFactory
例如,我在HashMap中有3个值,键idname 年龄。所以我希望在 TableView 中有3列与这个 HashMap 连接,并在包装​​数组后表示其值of Notes进入 ObservableList 并使用 TableView 方法 setItems()

which I need to somehow connect with a TableView via setCellValueFactory. For example I have 3 values in HashMap with keys "id", "name" and "age". So I want to have 3 columns in TableView which are connected with this HashMap and will represent its values after wrapping an array of Notes into ObservableList and using TableView method setItems().

推荐答案

只需使用值工厂返回给定键的映射值,例如

Just use value factories returning the value in the map for a given key, e.g.

final String key = "id";
TableColumn<Note, String> column = new TableColumn<>("ID");
column.setCellValueFactory(cd -> cd.getValue().items.get(key));

如果您需要使用 columnNames 您可以根据索引获取属性,例如

In case you need to use the keys from columnNames you could get the property based on the index instead, e.g.

final String index = 1;
TableColumn<Note, String> column = new TableColumn<>("1");
column.setCellValueFactory(cd -> cd.getValue().columnNames.size() <= index ?
                                    null
                                  : cd.getValue().items.get(cd.getValue().columnNames.get(index)));

请注意,根据使用的包,您可能需要将getter添加到注意 class。

Note that depending on the package used you may need to add getters to the Note class.

您还可以动态创建不存在的属性,使用 Map.computeIfAbsent 而不是获取,如果这是所需的行为:

You could also create non-existing properties "on the fly", by using Map.computeIfAbsent instead of get, if that is the desired behaviour:

items.computeIfAbsent(key, k -> new SimpleStringProperty())

这篇关于将TableView列连接到HashMap值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆