Data Management

Displaying data with JTables

JTables make it easy to display data in a Java application. This walk-through will show you how to build a sample application using JTables. We'll give you the source code too!

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’ll have to create this table before you can run the sample application.

JTables make displaying data in a Java application a simple task. In this two-part series, we'll show you how to use JTable technology to display data from a hypothetical Employee table in a sample Swing application and allow the user to modify, add, or remove records.

Getting connected
The first two classes to be presented are EmpJTable and SQLExceptionHandler. EmpJTable is the primary "driver" class that connects to the database and creates a new MainWin, which shows the data contained within the Employee table (Listing A).

SQLExceptionHandler traps any errors associated with connecting to the database (Listing B).

Displaying the data
Now, we need a way to display the data from our sample Employee table. Let’s look at code for the MainWin class. This class creates a window, defines its sizes and scrollbars, adds Insert and Delete buttons, assigns an editor for the data, and ensures that data is posted to the database if the window is closed. You can see the code in this Listing C.

Finally, let's take a look at the EmpTableModel class. This is the core class for our data presentation example, containing a SQL statement to retrieve the data, defining how the data is shown and in what cells, and specifying what the table is to do if a record is added or deleted. Thus, it provides the basic functionality you'd look for in a data display feature. The code for EmpTableModel is shown in Listing D.

In part two of this series, we’ll show you EmpDatabaseModifier, the class that actually posts a user’s changes to the database, and the EmpTable and EmpRow classes that handle displaying the data from our hypothetical Employee table.


Editor's Picks

Free Newsletters, In your Inbox