Dynamically populate jtable from database with data elements in JAVA.
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Vector;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
/**
*
* @author Pankaj
*/
public class ManageInvoice extends javax.swing.JPanel {
/**
* Creates new form ManageInvoice
*/
public ManageInvoice() {
initComponents();
Vector columnNames = new Vector();
Vector data = new Vector();
try
{
Connection conn=DBConnection.getDBConnection(); // DBConnection class with static method
//getDBConnection declaring database path
//and username and password.
String sql = "{CALL USP_MANAGE_INVOICE()}";
CallableStatement stmt=conn.prepareCall(sql); //If you are using stored procedure
ResultSet rs = stmt.executeQuery();
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
columnNames.add("S.NO.");
for (int i = 2; i <= columns; i++)
{
columnNames.addElement( md.getColumnName(i) );
}
int j =1;
while (rs.next())
{
Vector row = new Vector(columns);
row.add(j++);
for (int i = 2; i <= columns; i++)
{
row.addElement( rs.getObject(i) );
}
row.add(5, new Boolean(true));
data.addElement( row );
}
rs.close();
stmt.close();
}
catch(Exception e)
{
System.out.println(e);
}
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable(model)
{
// Returning the Class of each column will allow different
// renderers to be used based on Class
public Class getColumnClass(int c)
{
return getValueAt(0, c).getClass();
}
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col > 0) {
System.out.print("hi");
return true;
} else {
System.out.print("hi2");
return false;
}
}
};
TableColumn col;
for (int i = 0; i < table.getColumnCount(); i++)
{
col = table.getColumnModel().getColumn(i);
col.setMaxWidth(250);
}
jScrollPane1.setViewportView(table);
}
}
No comments:
Post a Comment