0

So I have this ArrayList filled with Objects and I need to convert it to an Object[][] to put it easily in a JTable.

Example :

I have an ArrayList<Animal>:

class Animal{
    String color;
    int age;
    String eatsGrass;
    // Rest of the Class (not important)
}

What I want from this is a JTable with the following column names :

Color - Age - Eats Grass?

My current method looks like this :

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

It works fine but is there an easier way to make this possible. I can not imagine myself using the same method for a JTable with 25 columns for example.

Sergey Kalinichenko
  • 697,062
  • 78
  • 1,055
  • 1,465
Yassin Hajaj
  • 20,892
  • 9
  • 46
  • 83

4 Answers4

1

Adding a new method in your Animal class would certainly help you:

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

And then:

for (int i = 0; i < ani.size(); i++){
    arrayForTable[i] = ani.get(i).getAttributesArray();
}
Fred Porciúncula
  • 7,984
  • 3
  • 38
  • 54
1

Add this to your Animal class.

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

Then, use a 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);
Andrew Mairose
  • 9,945
  • 11
  • 54
  • 96
0

what about just

   for (int i = 0 ; i < ani.size() ; i++){
            arrayForTable[i] = new Object[]{
             ani.get(i).getColor(), ani.get(i).getAge(),ani.get(i).getEatsGrass()};
}
user902383
  • 8,070
  • 8
  • 41
  • 62
0
for(int i = 0; i < ani.size(); i++) {
Animal animal = ani.get(i);
arrayForTable[i] = new Object[] {animal.getColor(), animal.getAge(), animal. getEatsGrass()};
}
ata
  • 8,625
  • 6
  • 37
  • 66