【问题标题】:Java Thread problem - updating GUIJava 线程问题 - 更新 GUI
【发布时间】:2011-03-26 11:53:09
【问题描述】:

我正在尝试使用线程在后台运行冗长的操作并更新 UI。 这是我想要做的:

  1. 单击按钮时,会显示一个带有消息“正在插入 DB”的 popupjframe
  2. 创建一个新线程以将 1000 条条目插入数据库。
  3. 插入条目后,我希望 popupjframe 消失并显示一个带有是,无按钮的 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 是否正确??

提前致谢。

【问题讨论】:

  • 在你的 runQueries() 方法中,你调用 updateProgress() 50000 次,每次创建一个新线程,而只有最后一个需要做任何有用的工作。它可能并不重,但它是不必要的开销,充其量是误导性代码。 ILMTitan 是正确的:SwingWorker 是正确的方法。

标签: java swing


【解决方案1】:

查看SwingWorker 的文档。它完全符合您的要求。创建一个子类,并从 doInBackground() 调用 runQueries,然后在 done() 中执行您的可运行对象所做的事情(减去 if queryNo 检查)。如果您不使用 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/

【讨论】:

  • 另见 download.oracle.com/javase/tutorial/uiswing/concurrency/…>.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-12
  • 1970-01-01
  • 1970-01-01
  • 2013-01-28
  • 2017-02-27
  • 2013-12-27
  • 1970-01-01
相关资源
最近更新 更多