简体   繁体   English

使用SwingWorker向jTable添加行并更新GUI

[英]Use SwingWorker to add rows to jTable and update the GUI

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. 我正在尝试创建一个jTable,单击该按钮后,一次添加一个行,并且从零开始只是一个数字,然后继续添加行直到行达到1000000。我正在使用SwingWorker的doInBackground,发布和处理方法以增加行计数器并添加每行,这意味着在添加行时gui不会冻结。 When run however, I can see the row number incrementing however it only adds one row and keeps changing that one row, ie 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!! 但是,当运行时,我看到行号增加了,但是它只添加一行并不断更改该行,即,将一行添加到表中,并且它的行号增加,所以我最后以一行结尾数量为1000000。以下是我的SwingWorker代码,任何帮助将不胜感激,这个问题一直让我无法入睡! :/ :/

    //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();

You're publish() ing the same Vector object over and over again. 您一次又一次地publish()相同的Vector对象。 Once you publish() it, you must create a new one. publish()一旦完成,就必须创建一个新的。 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. 要解决跳过行的问题,您只需要处理rowsList中的每个元素,而不是仅处理第一个元素。 Like so: 像这样:

@Override
protected void process(List<Vector> rowsList)
{
   for(Vector row : rowsList){
       DefaultTableModel tModel = (DefaultTableModel)jTable1.getModel();
       tModel.addRow(row);            
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM