我有一个Track对象的ArrayList.每个Track对象都有以下字段(所有字符串):
网址,标题,创作者,专辑,流派,作曲家
我想在JTable中显示这些轨道,每行是Track对象的一个实例,每列包含一个Track对象的属性.
如何使用JTable显示此数据?我已经使用了一个正确实现getValueAt()方法的AbstractTableModel.不过,我在屏幕上看不到任何东西.
或者只是使用数组更容易?
coo*_*ird 10
为了添加要在a上显示的内容JTable
,可以使用TableModel
添加要显示的项目.
添加一行数据DefaultTableModel
的addRow
方法之一是使用一个方法,该方法将采用Object
表示行中对象的s 数组.由于没有方法可以直接从中添加内容ArrayList
,因此可以Object
通过访问内容来创建一个s 数组ArrayList
.
下面的示例使用一个KeyValuePair
类,它是数据的持有者(类似于您的Track
类),它将用于填充a DefaultTableModel
以将表显示为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});
}
Run Code Online (Sandbox Code Playgroud)