Fundamentals of a Simple JTable


There are several techniques for creating and working with JTables, depending on the level of flexibility and functionality required.  The following describes a simple way to create and populate a JTable for display.

Declarations

// A JPanel to hold the JTable (this could also be a JApplet or any suitable Container)

JPanel p = new JPanel();
// A 2-D array of objects.  Each element in the array corresponds to a JTable cell.  
// Objects of any (single) class can be placed in this array.
// In this example, the objects will be Strings.
Object[][] values;  
// A String array containing the JTable's column headers
String[] colNames = {"Hdr 1", "Hdr 2", "Hdr 3"};
// The JTable itself
JTable table;
// A JScrollPane for the JTable
JScrollPane scrollPane;

Table Creation Pseudo-Code (for formatted numeric values)

Create the values 2-D array (declaring it does not create it, only a potential reference to it).

Fill the values array with formatted numeric values:

loop
  calculate a single value
  convert to formatted String
  place String in values[i][j]
end loop

Note: you can write a method to do all of the calculations and build and return a String[][] array, which can then be assigned to the values 2D-array and used as the first argument in the JTable constructor (see next step).  A String[][] array can be assigned to an Object[][] array.  In fact, any 2D Class[][] can be assigned to an Object[][].

Create the table object:

table = new JTable(values, colNames);

Create the scrollPane (you know how).

Set the Viewport parameters:

table.setPreferredScrollableViewportSize(new Dimension(300, 400));	// arg values are not critical
table.setFillsViewportHeight(true);

Make the scrollPane (with the table) visible in the JPanel, p:

p.add(scrollPane);
p.validate();	// tell p to re-draw itself

Removing an old JTable

In some cases, you may want to remove a currently visible JTable and replace it with a new one (possibly with a different number of rows or other altered property).  In cases like this, one technique is to remove the current JTable object and create a new one in its place.  The following steps can accomplish the removal:

Remove the scrollPane from the JPanel, p:

p.remove(scrollPane) ;	// reverse of add()

Set the scrollPane to null:

scrollPane = null;		// so it can be garbage collected

Set the JTable object to null:

table = null;

Cause the JPanel to re-draw itself (with nothing showing):

p.validate();
p.repaint();