Java 进度条与应用程序代码同时工作
我是java初学者。所以请让我知道如何同时运行进度条和我的应用程序代码。换句话说,我想让我的进度条在我的应用程序代码正在进行一些处理时递增。请详细说明它与代码。 我认为我必须同时添加两个线程。一个线程更新进度条线程,但我不确定它是否正确。 我已经编写了这段代码来增加进度条(硬编码)
class ProgressMonitor implements Runnable {
public void run() {
jProgressBar1.setStringPainted(true);
//run untill 100% complete
while (progress < 100) {
//update the progressbar
jProgressBar1.setValue(++progress);
jProgressBar1.repaint();
try {
//Sleep for .25 second
Thread.sleep(250);
} catch (InterruptedException ex) {
}
}
}
I am a beginner in java .So please let me know how can i simultaneously run the progress bar and my application code together.In other words i want to make my progressbar to increment as long as my application code is doing some processing.Please elaborate it with code.
What i think is that i have to add two threads simultaneously.One thread updating the progressbar thread but i am not sure whether its the right way or not.
i have written this code for incrementing progress bar (hard coded)
class ProgressMonitor implements Runnable {
public void run() {
jProgressBar1.setStringPainted(true);
//run untill 100% complete
while (progress < 100) {
//update the progressbar
jProgressBar1.setValue(++progress);
jProgressBar1.repaint();
try {
//Sleep for .25 second
Thread.sleep(250);
} catch (InterruptedException ex) {
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题基本上是长时间运行的任务阻塞了更新 GUI 的事件调度线程。一种解决方案是在
SwingWorker 中完成工作
。另请参阅本教程的Swing 中的并发课程以了解更多详细信息。
The problem is basically that the long running task blocks the Event Dispatch Thread that updates the GUI. One solution is to do the work in a
SwingWorker
.See also the Concurrency in Swing lesson of the tutorial for more details.
解决方案确实是使用
SwingWorker
。如果您想与JProgressBar
结合使用,我建议您查看JProgressBar
教程,其中有一个将SwingWorker
与JProgressBar
结合使用的示例。或者,您在此网站上进行快速搜索,找到类似 这个 的示例The solution is indeed to use a
SwingWorker
. If you want to use in in combination with aJProgressBar
, I would recommend to take a look at theJProgressBar
tutorial, which has an example usingSwingWorker
in combination withJProgressBar
. Or you do a quick search on this site and find examples like this one您可以在本主题中了解有关此内容和 SwingWorker 的更多信息:
管理 GUI和多任务应用程序中的 EDT
You can learn more about this and SwingWorker in this topic:
Manage GUI and EDT in a multi-task application