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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020