[英]How to use a JProgressBar in a different Thread?
I'm using POI in a function to fill the content of my excel document (it takes 10 seconds) and when i call my function I want to use a JProgressBar to see the progress, but the button and the program is block, i need to to make in other thread? 我在函数中使用POI来填充我的excel文档的内容(需要10秒),当我调用函数时,我想使用JProgressBar来查看进度,但是按钮和程序是阻塞的,我需要做其他线程? and how can I do it?
我该怎么办? an example of my code:
我的代码示例:
btnEjecutar.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
//the function
generarDocumento(nombre);
}
Event listeners are executed in the UI thread. 事件侦听器在UI线程中执行。 If an event listener takes a long time, the UI will stop working/lock up/block/hang.
如果事件侦听器花费很长时间,则UI将停止工作/锁定/阻止/挂起。
My guess is that the method generarDocumento()
takes a long time. 我的猜测是方法
generarDocumento()
需要很长时间。 If you want the UI to continue working, you must run it in a worker thread. 如果希望UI继续工作,则必须在辅助线程中运行它。 The Java documentation contains several examples how to do that: https://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html
Java文档包含如何执行此操作的几个示例: https : //docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html
The last example in the tutorial contains demo code how to update a progress bar: https://docs.oracle.com/javase/tutorial/displayCode.html?code=https://docs.oracle.com/javase/tutorial/uiswing/examples/components/ProgressBarDemoProject/src/components/ProgressBarDemo.java 本教程中的最后一个示例包含如何更新进度条的演示代码: https : //docs.oracle.com/javase/tutorial/displayCode.html? code =https : //docs.oracle.com/javase/tutorial/ uiswing / examples / components / ProgressBarDemoProject / src / components / ProgressBarDemo.java
Note: The linked content is copyrighted; 注意:链接的内容受版权保护; therefore I can't copy it here.
因此我不能在这里复制它。
Try to use an invokeLater, like the example bellow: 尝试使用invokeLater,例如下面的示例:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
generarDocumento(nombre);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.