使用 Objects 的字段从 ArrayList<Object> 创建 Object[][] 的简单方法

Easy way to make an Object[][] from an ArrayList<Object> with the fields of Objects

所以我有这个 ArrayList 充满了对象,我需要将它转换为 Object[][] 以便轻松地把它放在 JTable.

示例:

我有一个 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 使用相同的方法。

在您的 Animal class 中添加新方法肯定会对您有所帮助:

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

然后:

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

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

将此添加到您的 Animal class。

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);