题
我有一个Track对象的ArrayList。 每个Track对象都有以下字段(所有字符串):
网址,标题,创作者,专辑,流派,作曲家
我想在JTable中显示这些轨道,每一行都是一个Track对象的实例,每一列都包含一个Track对象的属性。
如何使用JTable显示此数据?我已经使用了一个正确实现getValueAt()方法的AbstractTableModel。不过,我在屏幕上看不到任何东西。
或者只是使用数组更容易吗?
解决方案
为了添加要在 <上显示的内容代码> JTable ,一个使用 TableModel
添加要显示的项目。
向 DefaultTableModel
添加一行数据的方法之一是使用 addRow
方法,它将采用对象的数组
表示行中的对象。由于没有方法直接从 ArrayList
添加内容,因此可以通过访问 ArrayList
的内容来创建 Object
的数组。
以下示例使用 KeyValuePair
类,它是数据的持有者(类似于 Track
类),它将用于填充 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});
}
其他提示
然后,我遇到的问题是我根本看不到问题。 这是我用来制作界面的代码:
public Interface(){
setSize(1024, 768);
setBackground(new Color(0,0,0));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new MenuBar());//simple JMenuBar implementation
table= new JTable();
table.setPreferredScrollableViewportSize(new Dimension(500, 500));
JScrollPane jsp = new JScrollPane(table);
add(jsp);
pack();
setVisible(true);
}
执行此代码后,我在另一个类中执行了多次代码:
((DefaultTableModel)mainInterface.table.getModel()).addRow(
new String[] {t.location,t.title,t.creator,t.album,t.genre,t.composer});
顺便说一句,是一个Track对象。
不隶属于 StackOverflow