简体   繁体   English

JProgressBar可以显示线程还在运行吗?

[英]Can a JProgressBar show that a thread is alive?

I'm trying to learn about threads and JProgressBar. 我正在尝试了解线程和JProgressBar。

I have a class that implements Runnable . 我有一个实现Runnable的类。 Let's say that the run() just sleeps for 20 seconds and displays "Hello World". 假设run()睡眠20秒并显示“ Hello World”。

Is it possible to create a JProgressBar that updates for as long as the thread is active? 是否可以创建一个JProgressBar,只要该线程处于活动状态,它就会更新?

If I had an int incrementer , could I do something like this (it doesn't work, obviously, but is there something along these lines?): 如果我有一个int incrementer ,我可以做这样的事情吗(显然,它不起作用,但是是否有类似的东西?):

while (Thread.isAlive()) {
    incrementer++;

    progress.setValue(incrementer);
    Rectangle progressRect = progress.getBounds();
    progressRect.x = 0;
    progressRect.y = 0;
    progress.paintImmediately( progressRect ); 
}

Thanks for any help. 谢谢你的帮助。

Yes, but you'll need to update the progress bar from the context of the thread, other wise you'll be blocking the a Event Dispatching Thread (EDT). 是的,但是您需要从线程的上下文中更新进度条,否则,您将阻止事件调度线程(EDT)。 This will mean you will need to synchronise the update with the EDT using something SwingUtilities.invokeLater. 这意味着您将需要使用SwingUtilities.invokeLater将更新与EDT同步。

Take a closer look at Concurrency in Swing for more details 仔细查看Swing中的并发以获取更多详细信息

You could also take a look at the indeterminate state of the progress bar, which can be used to indicate work in progress when you don't know how much work needs to be done 您还可以查看进度条的不确定状态,当您不知道需要完成多少工作时,该状态条可用于指示正​​在进行的工作

You could also use a SwingWorker which progress support via it's PropertyChange support 您还可以使用SwingWorker ,它通过它的PropertyChange支持来支持进度

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM