Running a JFrame with a JProgressBar(使用 JProgressBar 运行 JFrame)
问题描述
public void myMethod {
MyProgessBarFrame progFrame = new MyProgressBarFrame(); // this is a JFrame
progFrame.setVisible(true); // show my JFrame loading
// do some processing here while the progress bar is running
// .....
progFrame.setvisible(false); // hide my progress bar JFrame
} // end method myMethod
我有上面的代码.但是当我运行它时,在我关闭进度条 JFrame 之前,do some processing 部分不会处理.
I have the code above. But when I run it, the do some processing section does not process until I close the progress bar JFrame.
如何在 do 处理部分显示我的进度条并告诉 Java 继续?
How will I show my progress bar and tell Java to continue in the do processing section?
推荐答案
您遇到了并发和 Swing 的经典问题.您的问题是您正在主 Swing 线程、EDT 或事件调度线程上执行长时间运行的任务,这将锁定线程直到进程完成,阻止它执行包括与用户交互在内的任务和绘制 GUI 图形.
You've got a classic problem with concurrency and Swing. Your problem is that you're doing a long-running task on the main Swing thread, the EDT or Event Dispatch Thread, and this will lock the thread until the process is complete, preventing it from doing its tasks including interacting with the user and drawing GUI graphics.
解决方案是在后台线程中执行长时间运行的任务,例如 SwingWorker 对象提供的线程.然后您可以通过 SwingWorker 的发布/进程对更新进度条(如果是决定性的).有关这方面的更多信息,请阅读这篇关于Swing 中的并发 的文章.
The solution is to do the long-running task in a background thread such as that given by a SwingWorker object. Then you can update the progressbar (if determinant) via the SwingWorker's publish/process pair. For more on this, please read this article on Concurrency in Swing.
例如,
public void myMethod() {
final MyProgessBarFrame progFrame = new MyProgessBarFrame();
new SwingWorker<Void, Void>() {
protected Void doInBackground() throws Exception {
// do some processing here while the progress bar is running
// .....
return null;
};
// this is called when the SwingWorker's doInBackground finishes
protected void done() {
progFrame.setVisible(false); // hide my progress bar JFrame
};
}.execute();
progFrame.setVisible(true);
}
此外,如果这是从另一个 Swing 组件显示的,那么您可能应该显示一个模态 JDialog 而不是 JFrame.这就是为什么我在 SwingWorker 代码之后 在窗口上调用 setVisible(true) 的原因——这样如果它是一个模态对话框,它就不会阻止 SwingWorker 被执行.
Also, if this is being displayed from another Swing component, then you should probably show a modal JDialog not a JFrame. This is why I called setVisible(true) on the window after the SwingWorker code -- so that if it is a modal dialog, it won't prevent the SwingWorker from being executed.
这篇关于使用 JProgressBar 运行 JFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 JProgressBar 运行 JFrame
基础教程推荐
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01