Whenever you want to load a data from a query into a JTable, you can use the following JDBCTableModel.java class.
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
/*
* JDBCTableModel.java
*
* Created on March 1, 2006, 8:51 PM
*
*/
package tradetrakker;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Vector;
import javax.swing.table.AbstractTableModel;
/**
* Class for generating a JTableModel for a given Relational Database
* @author Vaibhav Pingle
*/
public class JDBCTableModel extends AbstractTableModel {
private int colCount = 0;
private int rowCount = 0;
/**
* Integer to store rowData
*/
private Object rowData[][];
/**
* Integer to store colData
*/
private String columnNames[];
private Vector<Vector<Object>> dataVector = new Vector<Vector<Object>>();
/**
* Creates a new JDBCTableModel with
* @param rs - ResultSet Object
*/
public JDBCTableModel(ResultSet rs) throws SQLException {
ResultSetMetaData rsmd = rs.getMetaData();
colCount = rsmd.getColumnCount();
columnNames = new String[colCount];
int i=0, j=0;
while(i<rsmd.getColumnCount()) {
columnNames[i] = rsmd.getColumnName(i+1);
i++;
}
rowCount = 0;
while(rs.next())
rowCount++;
rowData = new Object[rowCount][colCount];
i=0;
rs.beforeFirst();
while(rs.next()) {
j=1;
Vector<Object> rowV = new Vector<Object>();
while(j <= colCount) {
Object obj = rs.getObject(j);
if(rsmd.getColumnTypeName(j).compareTo("DATE") == 0 && obj != null)
obj = new SimpleDateFormat("dd-MM-yyyy").format(obj);
rowData[i][j-1] = obj;
rowV.add(obj);
j++;
}
getDataVector().add(rowV);
i++;
}
}
/**
* Returns the object located at (rowIndex, columnIndex)
* @param rowIndex - Integer value to select row
* @param columnIndex - Integer value to select column
* @return the value at (rowIndex, columnIndex)
*/
public Object getValueAt(int rowIndex, int columnIndex) {
return rowData[rowIndex][columnIndex];
}
/**
* Returns the Number of Rows in the JTable.
* @return the number of rows.
*/
public int getRowCount() {
return rowCount;
}
/**
* Returns the Number of Columns in the JTable.
* @return the number of Columns.
*/
public int getColumnCount() {
return colCount;
}
/**
* Returns the Name of the Column at index.
* @param column - Integer value to select Column.
* @return the name of the Column.
*/
public String getColumnName(int column) {
return columnNames[column];
}
public VectorVector<Vector<Object>> getDataVector() {
return dataVector;
}
public int getColumnIndex(String columnName) {
for(int i=0;i<columnNames.length;i++) {
if(columnName.equals(columnNames[i]))
return i;
}
return -1;
}
}
HOW TO USE THIS CLASS
Say you have executed a query as follows:
....
....
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM datatable;");
// create a table model
TableModel model = new JDBCTableModel(rs);
JTable table = new JTable();
table.setModel(model);
...
...
This is how you easily create your sql query to a JTable.
No comments:
Post a Comment