Populate JTable in Java

This program illustrates on how to use JTable in java program. The JTable is used to display and edit regular two-dimensional tables of cells.
  • Capable of connecting program to database using data source name (dsn) connection 
  • Capable of populating records from database to JTable. 
  1. Go to control panel > Administrative Tools > Data Sources (ODBC) 
  2. In ODBC Data Sources Administrator dialog, click the add button. 
  3. Select Microsoft Access Driver (*.mdb), thne click finish button 
  4. Data Source name: sirsuspect 
  5. Click the select button then browse the database 
Code snippet
import java.awt.*;
import java.io.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;

public class JTableDatabase extends JFrame{
public JTableDatabase() {
Vector columnNames = new Vector();
Vector data = new Vector();

try {
      Connection connect =DriverManager.getConnection("jdbc:odbc:sirsuspect");

      String sql = "Select * from tblstudent";
      Statement stmt = connect.createStatement();
      ResultSet rs = stmt.executeQuery( sql );
      ResultSetMetaData md = rs.getMetaData();
      int columns = md.getColumnCount();
      for (int i = 1; i <= columns; i++) {
      columnNames.addElement( md.getColumnName(i) );
      while (rs.next()) {
            Vector row = new Vector(columns);
            for (int i = 1; i <= columns; i++) {
                  row.addElement( rs.getObject(i) );
            data.addElement( row );
}catch(Exception e) {
      System.out.println( e );
JTable table = new JTable(data, columnNames);

JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );

JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel, BorderLayout.SOUTH );
public static void main(String[] args)

JTableDatabase frame = new JTableDatabase();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );


Programming Language: Java
Database: MS Access
Click Contact Us to request the source code

1 (mga) komento: