Wednesday, April 4, 2001 05:17 PM
I've done this very recently.
I started by sub-classing AbstractTableModel. The constructor for my custom
table model takes a string array to represent the column headers in the table,
and a two-dimensional array of Objects to represent the data. The signature
public MyCustomTableModel(String cols, Object data)
Naturally, certain methods have to be implemented as in any table model
class. Also, to retrieve any kind of custom objects from the table model, you
would have to store and pass the objects back and forth. (For example, if a row
in the table model represented some custom object that you were working with.
But, that is probably an answer to a different question.
To populate the table - and to get the image in a cell (assuming that an
image - not necessarily the same one - will be displayed in every row of a
particular column in the table), you would set up your 2-D array of Objects to
have at least one column store an image. Here's the way I did it (data
represents the 2D array of Object type i is the loop counter and represents each
// String in Column 1
data[i] = "Column 0 - Row " + i;
// getIcon() is a method we have that returns an ImageIcon from a resource
URI - image in column 2
data[i] = getIcon("NewJobFolder16.gif");
// String in column 3
data[i] = "Column 3 - Row " + i
After populating the data array and the column array, I instantiate a new
oModel = new MyCustomTableModel(cols, data);
Passing the array of column headers and the 2D array of data. Finally, I use
the setModel() method of the JTable to set the model and display the data:
Thats about it, at least in a somewhat abbreviated format. Hope it helps.