在JTable中显示对象的ArrayList内容的最简单方法是什么? [英] What is the easiest way to display the contents of an ArrayList of Objects in a JTable?

查看:210
本文介绍了在JTable中显示对象的ArrayList内容的最简单方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Track对象的ArrayList. 每个Track对象都有以下字段(所有字符串):

I have an ArrayList of Track objects. Each Track object has the following fields (all Strings):

网址,标题,创作者,专辑,流派,作曲家

url, title, creator, album, genre, composer

我想在JTable中显示这些轨道,每一行都是Track对象的实例,每一列都包含Track对象的属性之一.

I want to display these tracks in a JTable, with each row being an instance of a Track object, and each column containing one of the properties of a Track object.

如何使用JTable显示此数据?我使用了AbstractTableModel,它可以正确实现getValueAt()方法.不过,我在屏幕上看不到任何东西.

How can I display this data using a JTable? I've used an AbstractTableModel that implements the getValueAt() method correctly. Still, I dont see anything on the screen.

还是仅使用数组更容易?

Or is it easier just to use arrays?

推荐答案

为了添加要显示在

In order to add contents to display on a JTable, one uses the TableModel to add items to display.

DefaultTableModel添加一行数据的一种方法是使用

One of a way to add a row of data to the DefaultTableModel is by using the addRow method which will take an array of Objects that represents the objects in the row. Since there are no methods to directly add contents from an ArrayList, one can create an array of Objects by accessing the contents of the ArrayList.

以下示例使用KeyValuePair类作为数据的持有者(类似于您的Track类),该类将用于填充

The following example uses a KeyValuePair class which is a holder for data (similar to your Track class), which will be used to populate a DefaultTableModel to display a table as a JTable:

class KeyValuePair
{
    public String key;
    public String value;

    public KeyValuePair(String k, String v)
    {
        key = k;
        value = v;
    }
}

// ArrayList containing the data to display in the table.
ArrayList<KeyValuePair> list = new ArrayList<KeyValuePair>();
list.add(new KeyValuePair("Foo1", "Bar1"));
list.add(new KeyValuePair("Foo2", "Bar2"));
list.add(new KeyValuePair("Foo3", "Bar3"));

// Instantiate JTable and DefaultTableModel, and set it as the
// TableModel for the JTable.
JTable table = new JTable();
DefaultTableModel model = new DefaultTableModel();
table.setModel(model);
model.setColumnIdentifiers(new String[] {"Key", "Value"});

// Populate the JTable (TableModel) with data from ArrayList
for (KeyValuePair p : list)
{
    model.addRow(new String[] {p.key, p.value});
}

这篇关于在JTable中显示对象的ArrayList内容的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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