2015-10-13 149 views
0

所以我有這個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使用相同的方法。

+0

一個更好的辦法是使用合適的一個'TableModel'您的備份數據類型 –

+0

@SteveKuo是的,這是一個好主意。 –

回答

1

此加入你的Animal級。

public Object[] getDataArray() { 
    return new Object[]{color, age, eatsGrass}; 
} 

然後,使用TableModel

String columns[] = {"Color", "Age", "Eats Grass?"}; 

DefaultTableModel tableModel = new DefaultTableModel(columns, 0); 

for (Animal animal : ani) { 
    tableModel.addRow(animal.getDataArray()); 
} 

JTable animalTable = new JTable(tableModel); 
+0

謝謝!使用tableModel當然是做到這一點的最佳方式。接受! –

1

Animal類添加一個新的方法將一定會幫助你:

public Object[] getAttributesArray() { 
    return new Object[]{color, age, eatsGrass}; 
} 

然後:

for (int i = 0; i < ani.size(); i++){ 
    arrayForTable[i] = ani.get(i).getAttributesArray(); 
} 
+0

謝謝!確實是個好主意! –

0

怎麼樣只是

for (int i = 0 ; i < ani.size() ; i++){ 
      arrayForTable[i] = new Object[]{ 
      ani.get(i).getColor(), ani.get(i).getAge(),ani.get(i).getEatsGrass()}; 
} 
+0

Upvote因爲它回答了這個問題,但如果我有100個字段呢? –

+0

@YassinHajaj如果你的職業動物將有100個領域,你將有任何解決方案相同的問題。 – user902383

0
for(int i = 0; i < ani.size(); i++) { 
Animal animal = ani.get(i); 
arrayForTable[i] = new Object[] {animal.getColor(), animal.getAge(), animal. getEatsGrass()}; 
}