views:

374

answers:

1

I'm trying to create a jTable that, once a button is clicked, adds rows one at a time with just a number starting at zero and continues adding rows until it gets to row 1000000. I'm using a SwingWorker's doInBackground, publish and process methods to increment the row counter and and add each row, which means the gui doesn't freeze while the rows are being added. When run however, I can see the row number incrementing however it only adds one row and keeps changing that one row, i.e. one row is added to the table and and its row number increments so I end up with one row at the end with a number of 1000000. Below is the my SwingWorker code, any hep would be greatly appreciated, this problem has been giving me sleepless nights!! :/

    //inside the button's ActionPerformed method

    SwingWorker<Vector, Vector> worker = new SwingWorker<Vector, Vector>() {

    @Override
    protected Vector doInBackground()
    {       
        int i = 0;
        Vector v = new Vector();
        //while(!isCancelled())
        while(i < 100000000)
        {
            v.clear();
            //v = gen.runAlgorithm2();
            v.add(i);

            i++;             
            publish(v); 
        }

        return v;
    }

    @Override
    protected void process(List rowsList)
    {
       if(rowsList.size() > 0)
       {
           Vector row = (Vector)rowsList.get(rowsList.size() - 1);
           DefaultTableModel tModel = (DefaultTableModel)jTable1.getModel();

           //tModel.insertRow(0, row);
           tModel.addRow(row);            
       }

    }
    };
    worker.execute();
+3  A: 

You're publish()ing the same Vector object over and over again. Once you publish() it, you must create a new one. Try this instead:

@Override
protected Vector doInBackground()
{       
    int i = 0;
    while(i < 100000000)
    {
        Vector v = new Vector();
        v.add(i);

        i++;             
        publish(v); 
    }

    return v;
}

To solve the problem with skipped rows, you just need to process every element in rowsList, rather than only the first one. Like so:

@Override
protected void process(List<Vector> rowsList)
{
   for(Vector row : rowsList){
       DefaultTableModel tModel = (DefaultTableModel)jTable1.getModel();
       tModel.addRow(row);            
   }
}
Matt McHenry
Many thanks for your reply, this solved the problem of only one row being added to the table. However now the row numbers increment a few thousand between each row, I understand this is because the process method isn't run every time publish() is called and that the vectors are queued until process is called. I'm not sure how I could overcome this though and add every row, from 0 - 1000000.
KingCong
Thanks again for your help, it solved the problem!
KingCong