问题描述
我有一个 JAVA6 GUI处理数据导入到我们的数据库。我已经实现了一个有效的JProgressBar。我知道对GUI的更改必须通过事件派发线程来完成 - 我认为我没做(正确/完全)。
背景工作线程UploadWorker是通过传入在主程序中创建的JProgressBar构建的,并在完成后直接设置更改进度条的值:
//构造时,将其设置为主程序的JProgressBar。
JProgressBar进度;
protected Void doInBackground()抛出异常{
write(<! - Import from+ getCurrentTime()+ - > \\\
);
boolean chunked = false;
switch(importMethod){
//做一些导入
}
写(<! - 导入尝试已完成at+ getCurrentTime()+ - > \ n);
//这里对GUI的更改是
progress.setMaximum(0);
progress.setIndeterminate(false);
progress.setString(完成工作);
返回null;
}
这样可以正常工作,但有时候(并不总是)会让我看到几个NPE std out,用户抱怨:
线程中的异常AWT-EventQueue-0java.lang.NullPointerException
在javax.swing.plaf.basic.BasicProgressBarUI.updateSizes(未知来源)
...等...
无论如何,我相信我需要做些什么才能在正确的线程上执行这些更新,对吗?如何?
你可以创建一个新的Runnable来执行GUI更新并使用SwingUtilities.invokeLater在GUI线程中调用它/ p>
I have a JAVA6 GUI handling data import to our database. I have implemented a working JProgressBar. I understand that changes made to the GUI must be done via the event dispatch thread--which I do not think I am doing (properly/at all).
the background Worker thread, UploadWorker, is constructed by passing in the a JProgressBar created in the main program, and sets changes the value of the progress bar directly once it is finished:
// when constructed, this gets set to the main program's JProgressBar.
JProgressBar progress;
protected Void doInBackground() throws Exception {
write("<!-- Import starting at " + getCurrentTime() + " -->\n");
boolean chunked = false;
switch (importMethod) {
//do some importing
}
write("<!-- Import attempt completed at " + getCurrentTime() + "-->\n");
//here changes to the GUI are made
progress.setMaximum(0);
progress.setIndeterminate(false);
progress.setString("Finished Working");
return null;
}
This works fine, but sometimes(not always) throws me several NPE's in the std out, and users are complaining:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.plaf.basic.BasicProgressBarUI.updateSizes(Unknown Source)
...etc...
Anyway, I believe there is something I need to do to get these updates executed on the proper thread, correct? How?
You can just create a new Runnable that performs GUI updates and invoke it in a GUI thread using SwingUtilities.invokeLater
这篇关于Swing进度条通过Worker更新到EventDispatch线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!