Asked 7 years ago
27 Jan 2017
Views 8252
david

david posted

how to convert resultSet To TableModel in Java Swing ?

coding my first application for Swing (Java)
trying to fetch the result from MySQL and loading it to JTable
i have done

 dataTable = new javax.swing.JTable();
try {

	Class.forName(driver);
	conn = DriverManager.getConnection(url, user, password);
	System.out.println("connected");
	CallableStatement cs = conn.prepareCall("select id,title from employee");
 	ResultSet rs = cs.executeQuery();

} catch (SQLException e) {
	e.printStackTrace();
} catch (ClassNotFoundException e) {
 
	e.printStackTrace();
}



Now how to apply resultSet in setModel(TableModel dataModel)
need to convert resultSet To TableModel in Java Swing ? how to do it ?
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00


//  column Vector 
Vector column = new Vector();
column.addElement(new String("id"));
column.addElement(new String("title"));

//data Vector
Vector data = new Vector();
while (rs.next()) {
 	Vector temp = new Vector();
	temp.addElement(rs.getInt("id"));
	temp.addElement(rs.getString("title"));
	data.addElement(temp);
}
//append to JTable
dataTable.setModel(new javax.swing.table.DefaultTableModel(v,column));



many way to use resultSet with JTable , but i tried with Vector

Vector for column and Vector for data will used at public DefaultTableModel(Vector data, Vector columnNames)
Rasi

Rasi
answered Nov 30 '-1 00:00

rs2xml Jar
download the rs2xml jar . and add jar to project

this jar provide lib to convert resultSet to TableModel
so do import for DbUtils

import net.proteanit.sql.DbUtils;


and use DbUtils like this

dataTable.setModel(DbUtils.resultSetToTableModel(rs));


resultSetToTableModel will convert resultSet to TableModel

Post Answer