Adding a graphical interface to a Java program v42.5.4.1
With a little extra work, you can add a graphical user interface to a program. The next example shows how to write a Java application that creates a JTable
(a spreadsheet-like graphical object) and copies the data returned by a query into that JTable
.
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 EDB Postgres Advanced Server:
showEmployees()
creates a Statement
and uses the executeQuery()
method to execute an SQL query that generates an employee list:
As you'd 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 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 occur and display an appropriate message to the user:
The result of calling the showEmployees()
method is shown in figure: