Table of Contents Previous Next


6 Adding a Graphical Interface to a Java Program

NOTE: The following sample application is a method, not a complete application. To call this method, provide an appropriate main() function and wrapper class.
Before writing the showEmployees() method, you must import the definitions for a few JDK-provided classes:
The showEmployees() method expects a Connection object to be provided by the caller; the Connection object must be connected to the Advanced Server:
showEmployees() creates a Statement and uses the executeQuery() method to execute an SQL query that generates an employee list:
As you would expect, executeQuery() returns a ResultSet object. The ResultSet object contains the metadata that describes the shape of the result set (that is, the number of rows and columns in the result set, the data type for each column, the name of each column, and so forth). You can extract the metadata from the ResultSet by calling the getMetaData() method:
Next, showEmployees() creates a Vector (a one dimensional array) to hold the column headers and then copies each header from the ResultMetaData object into the vector:
With the column headers in place, showEmployees() extracts each row from the ResultSet and copies it into a new vector (named rows). The rows vector is actually a vector of vectors: each entry in the rows vector contains a vector that contains the data values in that row. This combination forms the two-dimensional array that you will need to build a JTable. After creating the rows vector, the program reads through each row in the ResultSet (by calling rs.next()). For each column in each row, a getter method extracts the value at that row/column and adds the value to the rowValues vector. Finally, showEmployee() adds each rowValues vector to the rows vector:
At this point, the vector (labels) contains the column headers, and a second two-dimensional vector (rows) contains the data for the table. Now you can create a JTable from the vectors and a JFrame to hold the JTable:
The showEmployees() method includes a catch block to intercept any errors that may occur and display an appropriate message to the user:
The result of calling the showEmployees() method is shown in Figure 6.1:
Figure 6.1 - The showEmployees Window

6 Adding a Graphical Interface to a Java Program

Table of Contents Previous Next