Heisenberg Heisenberg - 10 months ago 49
Java Question

How to create simple table in Java Swing?

I am working on a project "Hospital Management System" in Java Swing. Now on the records page I want to show all stored records of patients in a table format. But I have never worked with JTable in swing. Now when I tried to fetch records in a simple program, it is printing all records on console in for loop but when I go for JFrame and tried to fetch records on JTable, instead of making a table, it's showing a error message like:

Ex_test.java:51: cannot find symbol, symbol : constructor JTable(java.lang.String[],java.lang.String[][])
location: class javax.swing.JTable, JTable table=new JTable(column,data);

Can anyone tell me what is the problem in my code?

Database is MS-Access 2007.

import javax.swing.*;
import javax.swing.JTable;
import java.awt.event.*;
import java.awt.*;
import java.sql.*;

public class Ex_test extends JFrame
public static void main(String[] args)
Ex_test ob=new Ex_test();
int i=0;
String column[];
String data[][];
//JTable table;
public Ex_test()
String[] id=new String[15];
String[] name=new String[15];
String[] contact=new String[15];

Connection con;
Statement st;
ResultSet rs;

rs=st.executeQuery("select * from test");
String column[]={"ID","NAME","CONTACT"};
while (rs.next())
for (i=0;i<4 ;i++ )
String data[][]={{id[i],name[i],contact[i] }};
catch (Exception e)
JTable table=new JTable(column,data);

JTable table=new JTable(column,data); // wrong parameters

The constructor expects you to specify the data as the first parameter:

JTable table=new JTable(data, column);

Don't use Arrays for reading data from a database. You don't know how large to make the arrays. Instead use Vectors, since the DefaultTableModel will support Vectors.

Check out the TableFromDatabaseExample.java source code from Table From Database for some general code to get you started in populating a JTable with data from a database.

Also, don't use an empty catch block on the SQL code. You should display the exception.