Home > Articles > Programming > Java

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Modeling Your First Table Component

How do you create a table component? To begin, create an object from the JTable class. That object represents a table component. A quick look at the SDK documentation for JTable reveals seven constructors from which to choose. Although those constructors might look intimidating, each constructor does essentially the same thing: It either receives a previously created model (as an argument) or creates a model for the JTable object.

The simplest way to create a model for the JTable object is to create an object from the DefaultTableModel class. To create a DefaultTableModel object, you can call one of several constructors. One of the simpler constructors to call is DefaultTableModel(int nRows, int nCols). That constructor creates a model that holds values for all cells in an internal data Vector of row Vectors. (Initially, the data Vector contains nRows row Vectors.) The following code fragment calls that constructor to create a DefaultTableModel object with an internal data Vector containing four row Vectors:

DefaultTableModel dtm = new DefaultTableModel (4, 2);

DefaultTableModel makes it easy to assign column identifiers (objects that identify columns) to a table component's header. That occurs when you call DefaultTableModel's setColumnIdentifiers(Object [] colIDs) method. Each entry in the colIDs array references an object that identifies a column. The following code fragment stores two column identifiers in the previously created model:

String [] columnTitles =
{
  "Name",
  "Address",
};

dtm.setColumnIdentifiers (columnTitles);

NOTE

DefaultTableModel provides a getColumnName(int columnIndex) method that a table component calls when it needs to display the column identifier for the column indexed by columnIndex. The getColumnName(int columnIndex) method returns that identifier as a String, even though any object can be specified via setColumnIdentifiers(Object [] colIDs). It is possible to return a String because getColumnName(int columnIndex) uses the toString() method to convert an Object to a String.

What's a model without values? To help you initialize model cells to appropriate values, DefaultTableModel provides a setValueAt(Object value, int rowIndex, int columnIndex) method. When called, that method stores value in the row Vector entry indexed by columnIndex of the row Vector indexed by rowIndex. When a table component displays, the table component obtains that value from the model by calling DefaultTableModel's getValueAt(int rowIndex, int columnIndex) method. The following code fragment calls setValueAt(Object value, int rowIndex, int columnIndex) to initialize all cells in the previously created model:

String [] names =
{
  "John Doe",
  "Jane Smith",
  "Jack Jones",
  "Paul Finch"
};

String [] addresses =
{
  "200 Fox Street",
  "Apt. 555",
  "Box 9000",
  "1888 Apple Avenue"
};

int nrows = dtm.getRowCount ();

for (int i = 0; i < nrows; i++)
{
   dtm.setValueAt (names [i], i, 0);
   dtm.setValueAt (addresses [i], i, 1);
}

DefaultTableModel's getRowCount() method returns the number of rows assigned to the model. That would be nRows in the previously described constructor. Similarly, DefaultTableMethod's getColumnCount() method returns the number of columns.

TIP

When it comes to indexing cells by rows and columns, a table component consistently begins indexing with 0 instead of 1. The leftmost column is located at 0, the next-to-leftmost column is located at 1, and so on. Keep that in mind, and you will have no trouble indexing cells.

Now that you have a DefaultTableModel object whose contents have been initialized to appropriate cell values, it is time to create a JTable object. JTable's JTable(TableModel tm) constructor is appropriate for that task. You can pass the previously created DefaultTableModel object (as referenced by dtm) to that constructor because DefaultTableModel implements the TableModel interface. The following code fragment demonstrates the creation of a JTable object that uses that model:

JTable jt = new JTable (dtm);

The second task in creating a table component involves adding the JTable object to a container. It is common to place the JTable object in a JScrollPane object container so that horizontal and vertical scrollbars will appear if not all table component cells are visible. Then that JScrollPane object container is added to the content pane container of a Swing GUI's main frame window container. The following code fragment demonstrates this:

JScrollPane jsp = new JScrollPane (jt);

getContentPane ().add (jsp);

Now that a table component has been created, it needs to be sized and displayed. The following code fragment calls the setSize(int width, int height) and setVisible(boolean isVisible) methods that accomplish those tasks:

setSize (400, 110);

setVisible (true);

That is all you need to know to model your first table component. Listing 1 presents source code to a TableDemo1 application that combines the previous code fragments and displays the resulting table component (including cell values). To see what that table component looks like, refer back to Figure 1.

Listing 1: TableDemo1.java

// TableDemo1.java

import java.awt.*;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

class TableDemo1 extends JFrame
{
  TableDemo1 (String title)
  {
   // Pass the title to the JFrame superclass so that it appears in
   // the title bar.

   super (title);

   // Tell the program to exit when the user either selects Close
   // from the System menu or presses an appropriate X button on the
   // title bar.

   setDefaultCloseOperation (EXIT_ON_CLOSE);

   // Create a default table model consisting of 4 rows by 2
   // columns.

   DefaultTableModel dtm = new DefaultTableModel (4, 2);

   // Assign column identifiers (headers) to the columns.

   String [] columnTitles =
   {
     "Name",
     "Address",
   };

   dtm.setColumnIdentifiers (columnTitles);

   // Populate all cells in the default table model.

   String [] names =
   {
     "John Doe",
     "Jane Smith",
     "Jack Jones",
     "Paul Finch"
   };

   String [] addresses =
   {
     "200 Fox Street",
     "Apt. 555",
     "Box 9000",
     "1888 Apple Avenue"
   };

   int nrows = dtm.getRowCount ();

   for (int i = 0; i < nrows; i++)
   {
      dtm.setValueAt (names [i], i, 0);
      dtm.setValueAt (addresses [i], i, 1);
   }

   // Create a table using the previously created default table
   // model.

   JTable jt = new JTable (dtm);

   // Place the table in a JScrollPane object (to allow the table to
   // be vertically scrolled and display scrollbars, as necessary).

   JScrollPane jsp = new JScrollPane (jt);

   // Add the JScrollPane object to the frame window's content pane.
   // That allows the table to be displayed within a displayed 
   // scroll pane.

   getContentPane ().add (jsp);

   // Establish the overall size of the frame window to 400 
   // horizontal pixels by 110 vertical pixels.

   setSize (400, 110);

   // Display the frame window and all contained 
   // components/containers.

   setVisible (true);
  }

  public static void main (String [] args)
  {
   // Create a TableDemo1 object, which creates the GUI.

   new TableDemo1 ("Table Demo #1");
  }
}

Models in Depth

Models are created from classes that directly or indirectly, by way of a superclass, implement the TableModel interface. JTable provides a setModel(TableModel m) method that its constructors call to establish a table component's model. JTable also provides a getModel() method that returns a TableModel reference to the current model. To properly implement TableModel, classes provide implementations for those methods described in Table 2.

Table 2 TableModel Methods

Method

Description

addTableModelListener(TableModelListener l)

Adds the listener referenced by l to the model's array of listeners. When a change is made to the model, those listeners are notified.

getColumnClass(int columnIndex)

Returns a Class object that identifies the type of values that can be stored in column columnIndex's cells. That type determines the kind of rendering and editing performed on cells in that column.

getColumnCount()

Returns an integer containing the number of columns in the model.

getColumnName(int columnIndex)

Returns a String object containing the name of the column located at columnIndex. That name appears in a table component's header.

getRowCount()

Returns an integer containing the number of rows in the model.

getValueAt(int rowIndex, int columnIndex)

Returns an Object reference to an object containing the value of the cell located at (rowIndex, columnIndex).

isCellEditable (int rowIndex, int columnIndex)

Returns a Boolean true value if the cell located at (rowIndex, columnIndex) can be edited. Otherwise, returns false.

removeTableModelListener(TableModelListener l)

Removes the listener referenced by l from the model's array of listeners.

setValueAt(Object v, int rowIndex, int columnIndex)

Sets the value of the cell located at (rowIndex, columnIndex) to the object referenced by value.


Understanding the context in which TableModel methods are called is an important part of understanding a model. To begin, a model allows other objects to register themselves as listeners for model events. Those events are sent to registered listeners when a call is made to the setValueAt(Object v, int rowIndex, int columnIndex) method. The intent is to notify listeners that a cell's value has been changed. A program calls addTableModelListener(TableModelListener l) to register the object referenced by l with the model. Similarly, a program calls removeTableModelListener(TableModelListener l) to unregister the object referenced by l from the model.

NOTE

The TableModelListener interface declares a single tableChanged(TableModelEvent e) method that a model calls when the model changes. To find out what has changed, access various fields and methods in the TableModelEvent class.

The getColumnClass(int columnIndex) method is called (indirectly) by a UI delegate when it is preparing to edit or render (paint) the contents of a cell. The idea is to choose the appropriate editor or renderer based on the type of values stored in the cells of the column identified by columnIndex.

The getColumnCount() and getRowCount() methods are called by a UI delegate to help it navigate through a table component's cells (in response to keys pressed on the keyboard) and to help it paint cells. Those methods are also commonly called by a program that needs to initialize a model's cells.

The getColumnName(int columnIndex) method is called from JTable's addColumn(TableColumn tc) method during the automatic creation of a table component's columns. That happens when a JTable constructor is called that does not take a TableColumnModel argument. When called, addColumn(TableColumn tc) takes getColumnName(int columnIndex)'s return value and passes that value to a newly added table component column by calling tc's setHeaderValue(Object headerValue) method. Behind the scenes, a table component header's UI delegate (such as BasicTableHeaderUI) will call TableColumn's getHeaderValue() method to return the column name just before rendering that name in a column header cell.

The getValueAt(int rowIndex, int columnIndex) method is called from JTable's prepareRenderer(TableCellRenderer r, int rowIndex, int columnIndex) method. In turn, that method is called from a table component's UI delegate (such as BasicTableUI) when it is about to render the contents of a cell. (The cell's renderer is passed to prepareRenderer(TableCellRenderer r, int rowIndex, int columnIndex) as argument r.) Once getValueAt(int rowIndex, int columnIndex) returns a cell's value from the model, prepareRenderer(TableCellRenderer r, int rowIndex, int columnIndex) calls TableCellRenderer's getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int rowIndex, int columnIndex) method (via r) with the cell's value (passed in argument value) to configure a Component subclass object that will be returned from prepareRenderer(TableCellRenderer r, int rowIndex, int columnIndex) to the UI delegate, just before painting the cell. The setValueAt(Object v, int rowIndex, int columnIndex) method is typically called from an editor's editingStopped(ChangeEvent e) method to store a cell's value in the model once editing finishes.

Finally, the isCellEditable(int rowIndex, int columnIndex) method is called from JTable's editCellAt(int row, int col, EventObject e) method (which, in turn, is either directly or indirectly called from a UI delegate) to determine whether the cell's column's editor should edit the cell. If that method returns false, the cell will not be edited.

It would be most inconvenient if you had to create your own class that implements TableModel. To make your life easier, Sun provides a pair of classes that implement that interface. Those classes are AbstractTableModel and DefaultTableModel. As its name implies, AbstractTableModel is an abstract class. You cannot create an object from that class. Instead, AbstractTableModel serves as a superclass for more concrete subclasses, such as DefaultTableModel, from which you can create data models. So why have two classes? AbstractTableModel provides common methods (such as fireTableRowsUpdated(int firstRow, int lastRow)) for firing model events that distinguish between row insertions, deletions, and updates. Each "fire" method creates an event object that clearly identifies why the model has changed (such as an insert or a delete). It also identifies the rows that were affected. That event object is then sent to your program's listeners so that your program can take appropriate action. Because you really do not want to duplicate the "fire" methods in your model classes, and because AbstractTableModel does not "know" what data structure you will use to hold your cell values, it makes sense to have an abstract class—AbstractTableModel—that factors out commonality and a concrete subclass—DefaultTableModel—that provides a model's data structure and appropriate implementations of getValueAt(int rowIndex, int columnIndex) and setValueAt(Object v, int rowIndex, int columnIndex) to access that data structure.

DefaultTableModel provides its own methods, in addition to TableModel and AbstractTableModel's methods. For example, DefaultTableModel provides an insertRow(int rowIndex, Object [] values) method that inserts a new row at position, rowIndex, in the internal Vector of Vectors. Each column's value is taken from the values array. Similarly, DefaultTableModel provides a removeRow(int rowIndex) method that removes the row of cells located at rowIndex from the internal Vector of Vectors. When either method is called, an appropriate "fire" method is also called (behind the scenes) to inform all listeners that a row has been inserted or removed.

Listing 2 presents source code to a TableDemo2 application. That source code shows how to create a model from DefaultTableModel, register a TableModelListener object to listen for various changes to the model, call DefaultTableModel's insertRow(int rowIndex, Object [] values) method to append a row, and call DefaultTableModel's removeRow(int rowIndex) method to remove the last row.

Listing 2: TableDemo2.java

// TableDemo2.java

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.DefaultTableModel;

class TableDemo2 extends JFrame implements ActionListener,
                      TableModelListener
{
  JTable jt;

  TableDemo2 (String title)
  {
   // Pass the title to the JFrame superclass so that it appears in
   // the title bar.

   super (title);

   // Tell the program to exit when the user either selects Close
   // from the System menu or presses an appropriate X button on the
   // title bar.

   setDefaultCloseOperation (EXIT_ON_CLOSE);

   // Create a default table model consisting of 4 rows by 2 
   // columns.

   DefaultTableModel dtm = new DefaultTableModel (4, 2);

   // Populate all cells in the default table model.

   String [] names =
   {
     "John Doe",
     "Jane Smith",
     "Jack Jones",
     "Paul Finch"
   };

   String [] addresses =
   {
     "200 Fox Street",
     "Apt. 555",
     "Box 9000",
     "1888 Apple Avenue"
   };

   int nrows = dtm.getRowCount ();

   for (int i = 0; i < nrows; i++)
   {
      dtm.setValueAt (names [i], i, 0);
      dtm.setValueAt (addresses [i], i, 1);
   }

   // Register the current TableDemo2 object as a listener for table
   // model events.

   dtm.addTableModelListener (this);

   // Create a table using the previously created default table
   // model.

   jt = new JTable (dtm);

   // Add the table to the center portion of the frame window's
   // content pane.

   getContentPane ().add (jt);

   // Create a panel for positioning buttons.

   JPanel jp = new JPanel ();

   // Create a "Delete Last Row" button, register the current
   // TableDemo2 object as a listener to that button's action
   // events, and add that button to the panel.

   JButton jb = new JButton ("Delete Last Row");
   jb.addActionListener (this);
   jp.add (jb);

   // Create a "Append Row" button, register the current TableDemo2
   // object as a listener to that button's action events, and add
   // that button to the panel.

   jb = new JButton ("Append Row");
   jb.addActionListener (this);
   jp.add (jb);

   // Add the panel to the south portion of the frame window's
   // content pane.

   getContentPane ().add (jp, BorderLayout.SOUTH);

   // Establish the overall size of the frame window to 400
   // horizontal pixels by 175 vertical pixels.

   setSize (400, 175);

   // Display the frame window and all contained
   // components/containers.

   setVisible (true);
  }

  public void actionPerformed (ActionEvent e)
  {
   // Identify the button that initiated the event.

   JButton jb = (JButton) e.getSource ();

   // Obtain the button's label.

   String label = jb.getText ();

   // Either delete or append a row, as appropriate.

   if (label.equals ("Delete Last Row"))
   {
     DefaultTableModel dtm = (DefaultTableModel) jt.getModel ();
     int nRows = dtm.getRowCount ();
     if (nRows != 0)
       dtm.removeRow (nRows - 1);
   }
   else
   {
     DefaultTableModel dtm = (DefaultTableModel) jt.getModel ();
     String [] data = { "Name", "Address" };
     dtm.insertRow (dtm.getRowCount (), data);
   }
  }

  public void tableChanged (TableModelEvent e)
  {
   // Identify what has changed.

   switch (e.getType ())
   {
     case TableModelEvent.DELETE: System.out.println ("Delete");
                   break;
       
     case TableModelEvent.INSERT: System.out.println ("Insert");
                   break;

     case TableModelEvent.UPDATE: System.out.println ("Update");
   }
  }

  public static void main (String [] args)
  {
   // Create a TableDemo2 object, which creates the GUI.

   new TableDemo2 ("Table Demo #2");
  }
}

When you run TableDemo2 and click either of the Delete Last Row or Append Row buttons, you will notice that the table component automatically displays a new row or removes a row. Figure 2 shows the result of pressing Append Row to insert a row at the end of the table component.

Figure 2 Pressing the Append Row button inserts a row at the end of the table component.

Because only DefaultTableModel methods are called to perform those operations, and because the tableChanged(TableModelEvent e) method does not call any JTable methods, how is it possible for the table component's UI delegate to be informed of the change? The answer lies with JTable's setModel(TableModel m) method (that is called when a JTable object is being constructed). If you analyze that method's source code, you will notice that it registers the current JTable object as a TableModelListener with the model. As a result, DefaultTableModel's "fire" methods call JTable's tableChanged(TableModelEvent e) method (which notifies the UI delegate) along with TableDemo2's tableChanged(TableModelEvent e) method.

NOTE

In this article, if the word model appears by itself, that word refers to an object whose class directly or indirectly (by way of a superclass) implements the TableModel interface. If I qualify the word model with an adjective, as in column model or selection model, I am referring to a completely different entity. Keep that in mind as you read this article, and you shouldn't be confused.

  • + Share This
  • 🔖 Save To Your Account