Sunday, August 30, 2009

Swing ResultSet Column Table Component

Hear is a ready to use component for JTable in swing which will also show column titles. By default the JTable only displays the data which is strange although. This code is free and can be used easliy in commercial and opensource applications.
Yet this component does not have alignment facility depending on Integer or String or Date datatypes. Will update once done.

Steps to use the class
1. Create a class in package src.components.
2. Create a JTable and add it to JScrollPane.
JTable tblSuppliers = new JTable();
JScrollPane scrollpane = new JScrollPane(tblSuppliers);
3. Create the ResultSet,Create Model and set Model.
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(strQuery);
ResultSetTableModel qtm = new ResultSetTableModel();

Code for is as follows.
package src.components;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.table.AbstractTableModel;

public class ResultSetTableModel extends AbstractTableModel {
Vector cache;

int colCount;

String[] headers;

String currentURL;

public ResultSetTableModel() {
cache = new Vector();

public String getColumnName(int i) {
return headers[i];

public int getColumnCount() {
return colCount;

public int getRowCount() {
return cache.size();

public Object getValueAt(int row, int col) {
return ((String[]) cache.elementAt(row))[col];

public void setResultSet(ResultSet rs) {
cache = new Vector();
try {
ResultSetMetaData meta = rs.getMetaData();
colCount = meta.getColumnCount();

headers = new String[colCount];
for (int h = 1; h <= colCount; h++) {
headers[h - 1] = meta.getColumnName(h);

while ( {
String[] record = new String[colCount];
for (int i = 0; i < colCount; i++) {
record[i] = rs.getString(i + 1);
} catch (Exception e) {
cache = new Vector();


No comments:

Post a Comment