所以我有这个ArrayList
充满了对象,我需要将它转换为Object[][]
,以便于将它放在JTable
。简单的方法来使ArrayList对象[] [] <Object>与对象的字段
例子:
我有一个ArrayList<Animal>
:
class Animal{
String color;
int age;
String eatsGrass;
// Rest of the Class (not important)
}
我从此要与下列列名JTable中:
Color - Age - Eats Grass?
我现在的方法是这样的:
List<Animal> ani = new ArrayList();
// Fill the list
Object[][] arrayForTable = new Object[ani.size()][3];
for (int i = 0 ; i < ani.size() ; i++){
for (int j = 0 ; j < 3 ; j++){
switch(j){
case 1 : arrayForTable[i][j] = ani.get(j).getColor();break;
case 2 : arrayForTable[i][j] = ani.get(j).getAge();break;
default : arrayForTable[i][j] = ani.get(j).getEatsGrass();break;
}
}
}
它工作正常,但有没有更简单的方法来实现这一点。例如,我无法想象自己对具有25列的JTable
使用相同的方法。
一个更好的办法是使用合适的一个'TableModel'您的备份数据类型 –
@SteveKuo是的,这是一个好主意。 –