所以我有這個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是的,這是一個好主意。 –