Table From Database
Posted by Rob Camick on March 12, 2009
A JTable is frequently used to display data retrieved from a database. The JDK does not support this directly but there are a couple of standard ways to implement this functionality:
- use the ResultSet to implement the TableModel interface
- copy the data from the ResultSet to an existing TableModel
For the first approach, just search the web using “ResultSetTableModel” and you will find many different implementations. The trick will be to find an implementation with all the features you require, or one you can customize to meet your requirements.
For the second approach, you can use the DefaultTableModel, or you may find it easier to use the ListTableModel introduced in a previous blog entry..
For a simple example of how to do use the DefaultTableModel heck out the Table From Database example code posted below. The code will use the ResultSet to create a Vector of column names as well as a Vector containing the data for each row and column. The DefaultTableModel is then created using these Vectors. Then by overriding the getColumnClass() method of the JTable you can have the table choose the appropriate renderer and editor for each column of data.
The ListTableModel is now easier to use to meet this requirement as I have added new functionality to the class. A static method, createModelFromResultSet(…) has been added. You can now create the model and table in two lines of code:
ListTableModel model = ListTableModel.createModelFromResultSet( resultSet ); JTable table = new JTable( model );
Of course it is still up to you to create the SQL and execute the query to create the ResultSet, but creating the model and table couldn’t be any easier. A few things to know about the created model:
- the headings will automatically be formatted (ie. a column name of “PostalCode” will be formatted to “Postal Code”).
- by default the model will be uneditable (although this is easily changed at the model or column level using methods inherited by the ListTableModel).
- the column class is set appropriately for each column (ie. “Id” is rendered right justified as a number).