Java Reference
In-Depth Information
Using a GUI to Access a Database
All the programs in this chapter up to this point have been executed in command
windows, with the values retrieved from the database being displayed in a rather
primitive manner. Nowadays, of course we would expect such data to be displayed
in tabular format, using a professional-looking GUI. This can be achieved in Java
with very little extra code by making use of class JTable , which, as its name indi-
cates, is one of the Swing classes. An object of this class displays data in a table
format with column headings. The class has seven constructors, but we shall be
concerned with only one of these, the one that has the following signature:
JTable(Vector <rowData>, Vector <colNames>)
The fi rst argument holds the rows that are to be displayed (as a Vector of Vector s),
while the second holds the names of the column headings. Since each row contains
data of differing types, each of the 'inner' Vector s within our Vector of Vector s will
need to be a heterogeneous Vector . That is to say, it will need to be of type
Vector < Object> . This means that the full type for our Vector of Vector s will have the
following rather unusual appearance: Vector<Vector<Object>> . The Vector hold-
ing the headings will, of course, have type Vector<String> .
To allow for scrolling of the rows in the table, it will be necessary to 'wrap' our
JTable object in a JScrollPane , which will then be added to the application frame.
The example below uses our Accounts table to illustrate how a JTable may be used
to display the results of an SQL query.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import java.util.*;
public class JDBCGUI extends JFrame
private static Connection connection;
private Statement statement;
private ResultSet results;
private JTable table;
private JScrollPane scroller;
private fi nal String[] heading =
{"Account No.","Surname","First Names","Balance"};
private Vector<String> heads;
private Vector<Object> row;
private Vector<Vector<Object>> rows;
public static void main(String[] args)
Search WWH ::

Custom Search