Heisenberg
Heisenberg

Reputation: 161

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()
    {
        super("Array");
        String[] id=new String[15];
        String[] name=new String[15];
        String[] contact=new String[15];

        try
        {
            Connection con;
            Statement st;
            ResultSet rs;

            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            con=DriverManager.getConnection("jdbc:odbc:test");
            st=con.createStatement();
            rs=st.executeQuery("select * from test");
            String column[]={"ID","NAME","CONTACT"};
            while (rs.next())
            {
                    id[i]=rs.getString("id");
                    name[i]=rs.getString("sname");
                    contact[i]=rs.getString("contact");
                    i++;
            }   
            for (i=0;i<4 ;i++ )
            {
                System.out.println(""+id[i]+name[i]+contact[i]);
                String data[][]={{id[i],name[i],contact[i] }};              
            }           
        }
        catch (Exception e)
        {
        }   
        JTable table=new JTable(column,data);
        setSize(1000,1000);
        setVisible(true);       
    }   
}

Upvotes: 4

Views: 10866

Answers (1)

camickr
camickr

Reputation: 324157

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.

Upvotes: 6

Related Questions