2015-10-13 152 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()}; 
}