Search code examples
javaswingjtabletablemodel

Same dataset, two different JTables


I have some data I have to show through two JTables; the data is the same, but each table will have to show it a little differently. Also, I receive the data from an external connection (JMS in this case, but it doesn't really matter, it could be a DB, or whatever).

Being that I am new to Swing, I am still a little confused about who should fire the events, who should listen to them and how to make so that for a modification to my dataset I will have both the tables to update.

Now, a little example of my dataset structure as well as some dummy data:

class Student{ String name; Classroom classroom; boolean goodStudent}
class Classroom{ Sting name; List<String> coursesTaught; List<Student> students;}

public List<Classroom> classes;

Basically, my dataset will be the classes field in a Controller class and the two JTables will have to show things in different ways. Namely, Table1 will have to show something like:

Classroom Name | Courses
4a             | CS101, CS102, CS103
4b             | BM101, CS102
4c             | I101, CS4100

So basically, for each Classroom, the list of courses.

Table2 should instead show things like:

Student Name   | Good?
Mark Spencer   | true
Philippe Mann  | true
Tom Sayer      | false

I should see ALL the students, from all classrooms.

As you can see, the data is the same, but it is shown in different way. What I would like to do is that, when my data changes, the tables will automatically update too. For what I understood so far, I will have to subclass AbstractTableModel and create two different TableModels for the kind of data I want to show; what I don't get is:

  • How will the Models get their data, once some change happens?
  • Who should notify the models of this change?
  • Is it enough to call "fireTableXXXEvent()" to trigger the view refresh?

I hope I made myself clear enough... In any case, thank you very much! Bye


Solution

  • You are right. You need 2 AbstractTableModels. Suppose you have the list List classesList classes as main data source. The first model row count will just return size() of the list. The second one will return sum of Students counts for each classroom. Column count for both models is 2. The inteeresting methods are getValueAt/setValueAt you have to find proper row. For the first list it's easy just appropriate list item. For the second table model you have to calculate proper row and then iterate through the list of Students. Suppose something is changed in DB. You retrieve a new List. You can either find what's changed, which rows/cols were inserted/removed/changed or just replase the data source list in both models and fire structure changed event to let JTable completely refresh content. Thre is no automatic update of models. You can write e.g. timer to check the changes each second/minute/hour or refresh on reopening the dialog/frame where the table is shown.