2

Hi I have an arraylist of a class I created called Pets which has the variables below

private String name;
private String species;
private int age;

I wanted to display this arraylist into a jTable and I did that succesfully by using defaultTableModel and calling setModel().

However I needed to add a sorting and filtering function for the Jtable. I took a look at the java tutorials were they were creating a subclass of AbstractTableModel in order to sort and filter. However they were using arrays to store the data. So I tried modifying the code to use an arraylist isntead but Im stuck with this method

public Object getValueAt(int row, int col) {
    return data[row][col];
}

How do I get all the values from one object from th arraylist?

Any help will be greatly appreciated. Thanks in advance.

1
  • 1
    I think JTable supports sorting and filtering out of the box without writing a data model just enabling some properties. Apr 22, 2012 at 0:22

2 Answers 2

3

Does your ArrayList hold a row that is it's own type of object? If so, and if your ArrayList is a generic ArrayList<RowItem> then you could do something like:

@Override
public Object getValueAt(int row, int col) {
  if (row > getRowCount()) {
     // throw an exception
  }
  RowItem rowItem = rowItemList.get(row);
  switch (col) {
  case 0:
     return rowItem.getName();
  case 1:
     return rowItem.getLastSpecies();
  case 2:
     return rowItem.getAge();
  }
  return null; // or throw an exception
}
0
3

You can try this:

public Object getValueAt(int row, int col) {
    switch(col) {
        case 0:
           return ((Pets)data.get(row)).getName();
        case 1:
           return ((Pets)data.get(row)).getSpecies();
        case 2:
           return ((Pets)data.get(row)).getAge();          
    }
    return null;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.