Nilesh
Nilesh

Reputation: 2168

Reference to row in JTable

JTable stores rows which can be added, deleted, shuffled, dynamically. In my implementation row represent a Download, whose progress can be dynamically updated, by passing value of one of the unique attribute called id. But how do I map id with actual row?

Iterating over the column is not efficient approach. Is there any way to dynamically synchronize Hashmap<ID,Object[]> with JTable, such that given a key I can update corresponding row, and vice versa?

private dftTasks=new DefaultTableModel();
public void addTask(String type, String name, int progress, int sessionID) {
    Object[] rowData={type,name,new Integer(progress),new Integer(sessionID)};      
    dftTasks.addRow(rowData);
}

public void updateProgress(int sessionID, int progress) {
    int i = dftTasks.getRow(sessionID); //<--alternative to this method
    dftTasks.setValueAt(new Integer(progress), i, 2); //2nd column=Progress
}

Upvotes: 1

Views: 509

Answers (2)

Alex
Alex

Reputation: 4473

You just answered your own question - use HashMap:

private dftTasks=new DefaultTableModel();
Hashmap<Integer,Object[]> map = new Hashmap<Integer,Object[]>();
public void addTask(String type, String name, int progress, int sessionID) {
        Object[] rowData={type,name,new Integer(progress),new Integer(sessionID)};
        map.put(progress,rowData);      
        dftTasks.addRow(rowData);
    }

    public void updateProgress(int sessionID, int progress) {
        //int i = dftTasks.getRow(sessionID); //<--alternative to this method
        Object[] i = map.get(sessionID);
        dftTasks.setValueAt(new Integer(progress), i, 2); //2nd column=Progress
    }

To do vice versa and listen for changes use TableModelListener to listen for the changes,

Upvotes: 1

copeg
copeg

Reputation: 8348

  1. Create a class to encapsulate the data (eg type, name, progress, and id).
  2. Store instance of (1) in a List, and if necessary any other data structure for quick access (eg a Map keyed by id). The order of this List is the row order of the table.
  3. Extend AbstractTableModel, and implement the necessary methods to return the values from the List from (1) and (2) based upon the row/column.
  4. When values of the instances from (2) are changed (eg, the progress updated), call fireXXX from within the implementation in (3) (the source of DefaultTableModel is a good example of how this is done)

Upvotes: 1

Related Questions