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
  • 714,442
  • 84
  • 1,110
  • 1,523
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89

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
  • 8,533
  • 3
  • 40
  • 57
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
  • 10,615
  • 12
  • 60
  • 102
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,420
  • 8
  • 43
  • 63
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,853
  • 8
  • 42
  • 68