使用 SwingWorker 向 jTable 添加行并更新 GUI
我正在尝试创建一个 jTable,一旦单击按钮,一次添加一行,其中的数字从零开始,并继续添加行,直到到达第 1000000 行。我正在使用 SwingWorker 的 doInBackground、publish 和process 方法来增加行计数器并添加每一行,这意味着在添加行时 gui 不会冻结。但是,当运行时,我可以看到行号递增,但它只添加一行并不断更改该行,即一行被添加到表中,并且其行号递增,因此我最终会在最后得到一行,并带有数量为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();
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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您一遍又一遍地
publish()
相同的Vector
对象。一旦您publish()
它,您必须创建一个新的。试试这个:要解决跳过行的问题,您只需处理
rowsList
中的每个元素,而不仅仅是第一个元素。就像这样:You're
publish()
ing the sameVector
object over and over again. Once youpublish()
it, you must create a new one. Try this instead:To solve the problem with skipped rows, you just need to process every element in
rowsList
, rather than only the first one. Like so: