1

I am newbie in JTable, maybe I don't understand something.

Let's suppose I have ArrayList of 1000 Students (id, name, surname, age). And I want to show all students in JTable. As far as I understood I must create StudentTableModel that extends AbstractTableModel and set StudentTableModel to JTable. Therefore we can consider StudentTableModel as an "adapter" between our ArrayList and the table. On the internet I found such example implementation of getValueAt:

 public Object getValueAt(int row, int col) {
      Student student = arrayList.get(row);
      switch (col) {
      case 0:
        return student.getId();
      case 1:
        return student.getName();
      case 2:
        return student.getSurname();
      case 3:
        return student.getAge();
      }
    }

The problem is that having 1000 students (rows) and 4 field (columns) we will run this switch 4000 times. Please explain what I do wrong or tell about a better solution.

Paul Samsotha
  • 188,774
  • 31
  • 430
  • 651
  • there couldnt be some problem with numbers of Items, – mKorbel May 07 '14 at 07:49
  • 1
    There's nothing wrong with that. If you think 4000 is a big number, don't worry, the processor doesn't consider that anything. The only way this would be a problem is if you were to perform a database query every time, even then the switch wouldn't be the problem but the actual retrieval of data. I suggest that you don't try to think about performance before you have actual proof that it's an issue. – Kayaman May 07 '14 at 07:51
  • @mKorbel Please explain what you mean. –  May 07 '14 at 07:51
  • there are two options, depends of direction 1. you would need to use array for (and then to use and override) AbstractTableModel in the case that this array is used as primary data source for/to whole programm, 2. otherwise to use DeafultTableModel, then all values are accesible from this model for/to whole program – mKorbel May 07 '14 at 08:03
  • `The problem is that having 1000 students (rows) and 4 field (columns) we will run this switch 4000 times.` In addition to Kayaman's comment, the JTable will only dispay 20-30 rows at a time so the code will only be executed 80-120 times when you scroll. – camickr May 07 '14 at 15:35

2 Answers2

2

Having 1000 students (rows) and 4 field (columns), we will run this switch 4000 times.

The premise is false, but you should profile to verify. JTable uses the flyweight pattern for cell rendering, so only visible cells will be examined. This simplified example illustrates the essential mechanism. This related example scales well into the thousands of rows.

Community
  • 1
  • 1
trashgod
  • 196,350
  • 25
  • 213
  • 918
0

You can store students in a Map which maps row to student attributes.

Map<Integer, Object[]> students;

The method will look so:

public Object getValueAt(int row, int col) {
    return students.get(row)[col];
}
ka3ak
  • 1,740
  • 1
  • 20
  • 39