Smitty
Smitty

Reputation: 403

Java: Proper way to update TableModel's data?

This is a simplifed version of what I'm trying to do. I have a map which maps an integer id to a list of strings. One of these lists from the map is displayed by a JTable at all times. (Depending on which id needs to be displayed) All information for the map is coming from a database, and is constantly being added to and removed from. My DataClass which stores the full map and receives the updates from the database:

DataClass {
   Map(Integer, List<String>) map;

   // TabelModel gets list here
   public List<String> getList(int id) {
       return map.get(id);
   }

   // Updates from database come here
   public updateList(int id, String info) {
       if (map.containsKey(id) {
          map.get(id).add(info);
       }
       else {
          map.put(id, new List<String>(info));
       }
   }

   // Remove from list, etc all down here
   ...
}

My Table model class:

MyTableModel extends DefaultTableModel {
    List data;

    public void updateData(int id) {
        data = getList(id)
        fireTableDataChanged();
    }

    ... All the other stuff needed ...
}

Since database updates occur in batches, I know that at the end of a batch I have to update the table. So the DataClass informs the UI class which informs the table to update. This causes the updateData(id) to be called which retrieves a new set of data from the DataClass and calls fireTableDataChanged();

My Question are:

  1. Is this the right way to go about updating/storing the data in the table?
  2. Should getList return a clone of the data? If I just return the reference all updates from the database would be accessing that same reference and since these updates aren't running in the EDT wouldn't that be bad/frowned upon/wrong?
  3. How can I do this using Java Events? PropertyChangeEvent? If so, how?

Upvotes: 1

Views: 1178

Answers (1)

trashgod
trashgod

Reputation: 205885

To the extent that your questions are related,

  1. No; when new data is available, your updateData() method should update the internal data structure of your TableModel and fire an appropriate event; because DefaultTableModel knows nothing of your List, extend AbstractTableModel, as shown here; the JTable will update itself in response.

  2. No; your database access layer should retain no references to queried objects, and no cloning should be necessary; forward queried objects to your display layer from the process() method of SwingWorker, or similar.

  3. Use a TableModelListener to learn when and how the TableModel has changed; update the database accordingly.

Upvotes: 1

Related Questions