繁体   English   中英

Java线程问题 - 更新GUI

[英]Java Thread problem - updating GUI

我正在尝试使用线程在后台运行lenghty操作并更新UI。 这是我正在尝试做的事情:

  1. 按一下按钮,显示一个带有“插入数据库”消息的popupjframe
  2. 创建一个新线程,将1000个条目插入数据库。
  3. 当插入条目时,我希望popupjframe消失并显示带有yes,no按钮的joptionpane
  4. 单击是按钮我想显示另一个框架与报告/插入过程的详细信息

这是我的代码:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//display popupframe first

jFrame1.pack();
jFrame1.setVisible(true);
jFrame1.setLocationRelativeTo(getFrame());
Thread queryThread = new Thread() {
public void run() {
runQueries();
}};
queryThread.start();
}

//runqueries method inserts into DB

private void runQueries() {
for (int i = 0; i <= 50000; i++) {
insertintoDB();
updateProgress(i);
}
}

//update the popupjframe
private void updateProgress(final int queryNo) {
SwingUtilities.invokeLater(new Runnable() {
 public void run() {
if (queryNo == 50000) { //means insertion is done
jFrame1.setVisible(false);

int n = JOptionPane.showConfirmDialog(getFrame(), menuBar, null, JOptionPane.YES_NO_OPTION);

if (n == 1) { //NO option was selected
return;}
else
//display another popupframe with details/report of inserting process
}});
}
  1. 我的方法是否正确?
  2. 我如何以及何时停止/中断“queryThread”?
  3. 如果我在runqueries方法本身(在for循环之后)创建popupjframe并显示joptionpane,这是正确的吗?

提前致谢。

查看SwingWorker的文档。 它完全符合您的要求。 创建一个子类,并从doInBackground()调用runQueries,然后在done()中执行runnable所做的操作(减去if queryNo check)。 如果您不使用java 1.6,则可以使用此类的第三方版本。

class DbSwingWorker extends SwingWorker<Void, Integer> {

    @Override
    protected Void doInBackground() throws Exception {
        for (int i = 0; i <= 50000; i++) {
            insertintoDB();
            publish(i); //if you want to do some sort of progress update
        }
        return null;
    }

    @Override
    protected void done() {
        int n = JOptionPane.showConfirmDialog(getFrame(), menuBar, null, JOptionPane.YES_NO_OPTION);

        if (n == 1) { //NO option was selected
            return;
        } else {
            //display another popupframe with details/report of inserting process

        }
    }
}

原始的非1.6版本可以在这里找到: https//swingworker.dev.java.net/

暂无
暂无

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

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