Data Management

A JTable application that updates and displays data

In the second part of this two-part series, we complete our example JTable application with the code to handle database updates and actually display the data. As always, we're giving away the source.

Due to an editorial oversight, this article was originally posted with errors in the example source code. We have corrected these errors and would like to offer a heartfelt apology to all members who may have been inconvenienced by them.

There are three things you should know to successfully run the code provided in this article:
  • ·        The EmpJTable class is the “main” class and is the one that should be executed.
  • ·        EmpJTable has three static member variables—DB, USR and PWD—which should be changed to reflect the correct ODBC connection string, user id, and password.
  • ·        The code assumes that a table named “employee” containing the fields EmpId, EmpLastName, and EmpFirstName exists in an ODBC-compliant database. You will have to create this table before you can run the sample application.

In the first part of this series, “Displaying data with JTables,” we looked at EmpJTable, SQLExceptionHandler, MainWin, and EmpTableModel, sample Java classes that connect to a database and provide basic display functionality for data from a hypothetical Employee table. In this article, we’ll complete our example, reprinted from TechRepublic’s Java TechMail. We’ll show you EmpDatabaseModifier, EmpTable, EmpRow, and ObjectToIntMapclasses, which take care of posting changes and displaying the data.

Modify and display your data
We'll start by taking a look at the EmpDatabaseModifier. This is the class that actually handles changes to the database. It keeps track of the modifications made to the Employee table in vectors (which are called for use by EmpTableModel), and it applies all updates upon exiting the application. The source for the EmpDatabaseModifier class appears in Listing A.

Next, let’s look at EmpTable. This class is the area with the scrollPane, which contains the Employee data. The scrollPane, along with the buttonPanel, make up the components of the display. You can see the EmpTable source in Listing B.


This brings us to EmpRow, which represents a row from the Employee table and contains the requisite fields (Listing C).

Finally, we have ObjectToIntMap, a helper class that maps an object to an integer (used in the EmpTableModel and EmpDatabaseModifier), which is shown in Listing D.

So there you have it: all the elements needed for a working JTable application.

Java Q&A
Need a Java answer? TechRepublic’s developers may be able to help. Send us your Java question, and our Java Q&A staff will take a crack at it.


Editor's Picks

Free Newsletters, In your Inbox