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 ResultSetTableModel.java in package src.components.
2. Create a JTable and add it to JScrollPane.
JTable tblSuppliers = new JTable();
tblSuppliers.setVisible(true);
JScrollPane scrollpane = new JScrollPane(tblSuppliers);
pnlCenter.add(scrollpane,BorderLayout.CENTER);
3. Create the ResultSet,Create Model and set Model.
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(strQuery);
ResultSetTableModel qtm = new ResultSetTableModel();
qtm.setResultSet(rs);
tblSuppliers.setAutoCreateColumnsFromModel(true);
tblSuppliers.setModel(qtm);


Code for ResultSetTableModel.java 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 (rs.next()) {
String[] record = new String[colCount];
for (int i = 0; i < colCount; i++) {
record[i] = rs.getString(i + 1);
}
cache.addElement(record);
}
fireTableChanged(null);
} catch (Exception e) {
cache = new Vector();
e.printStackTrace();
}
}

}

No comments:

Post a Comment