vijay
vijay

Reputation: 1139

How to load the JTable faster?

I have created 2 JTable in my class,

for the first JTable the data comes from server to arraylist and then to JTable

for the second JTable the data comes from local access database to JTable (no arraylist)

Both JTables will be displayed together when user click a button.

But it takes up to 1min to load and display both jtable on the interface.

Is there any way to load them faster?

Sample code Table1

data = new ArrayList<Person>();
try
    {
        conn = dc.getConnection();
        stmt = conn.prepareStatement(query);
        rs = stmt.executeQuery();

        while(rs.next())
        {
             String[] rowData = new String[4];
            for(int i=1;i<=4;i++)
            {
                rowData[i-1] = rs.getString(i);                    
            }
            //database to arraylist
            data.add(new Person(rowData[0],rowData[1],rowData[2],rowData[3]));
        }

String[] colNames = {"LastName","FirstName","Email","Department"};
model = new DefaultTableModel(colNames,data.size())

sorter = new TableRowSorter<TableModel>(model);
    int row = 0;
    //arraylist to JTable
    for(Person p:data)
    {
        model.setValueAt(p.lastName, row, 0);
        model.setValueAt(p.firstName, row, 1);
        model.setValueAt(p.email, row, 2);
        model.setValueAt(p.dept, row, 3);
        row++;

    }
    table.setModel(model);
    table.setRowSorter(sorter);

Sample code of Table2

String[] colNames = {"Name","Email","Department","Status"};
model = new DefaultTableModel(colNames,500);
table.setModel(model); 

try
    {
        conn = ac.getConnection();
        stmt = conn.prepareStatement(insert);
        rs = stmt.executeQuery();
        int row = 0;   
        while(rs.next())
        {
            String[] rowData = new String[4];
            for(int i=1;i<=4;i++)
            {
                rowData[i-1] = rs.getString(i);
            }
            //access database to jTable
            model.setValueAt(rowData[0], row, 0);
            model.setValueAt(rowData[1], row, 1);
            model.setValueAt(rowData[2], row, 2);                
            model.setValueAt(rowData[3], row, 3);                
            row++;  

        }

Upvotes: 0

Views: 1368

Answers (2)

Hasanka Rathnayake
Hasanka Rathnayake

Reputation: 137

you can load data to jtable easily through this

DefaultTableModel tm = (DefaultTableModel) jTable1.getModel();
tm.addRow(new Object[] {name,age,tel});

name age tel are values in column1, column2, column3

Upvotes: 2

camickr
camickr

Reputation: 324207

The delay is caused by the time required to do the database queries. So you want to make sure you are doing two separate queries, each on a different thread so one query is not waiting for the other to finish.

This can be done by creating 2 SwingWorkers, one for the server access and the other for the local access.

Upvotes: 3

Related Questions