【发布时间】:2016-05-23 14:38:25
【问题描述】:
这是我第一次使用进度条,我遇到了一个问题,除了我尝试从任何地方调用它的setValue(x),它保持在 0% 并在我的方法例程之后直接进入 100%完成。
我尝试创建一个扩展 Thread 的内部类,然后在我尝试在我的“main”方法中启动一个新 Thread 之后,最后我尝试使用 Observer。这些似乎根据这篇文章有效,但不幸的是对我来说不是
Update JProgressBar from new Thread
Problem making a JProgressBar update values in Loop (Threaded)
请问有人可以帮我吗???
public class MainClass {
private void checkFiles() {
Task task = new Task();
task.start();
//here I have some Files validation...I don't think it is important to solve the progressbar problem
//so it will be ommited
//in this point I tried to call update to test the observer solution I found in another post here
//task.update(null, null);
JOptionPane.showMessageDialog(this, "Done!");
//here the bar jumps from 0% to 100%
}
private class Task extends Thread implements Observer {
public Task() {
}
//Dont bother with the calculum as I haven't finished working on them....
//The relevant thing here is that it starts a new Thread and I can see the progress
//increasing on console using system.out but my progress bar still don't change from 0%.
public void run() {
int maxSize = 100;
final int partsSize = maxSize / listaArquivosSelecionados.size();
while (listFilesValidated.size() != listFilesToValidate.size()) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
int progress = listFilesValidated.size() * partsSize;
System.out.println("Progress" + progress);
progressBar.setValue(progress);
}
});
try {
Thread.sleep(100);
}
catch (InterruptedException e) {}
}
}
//Just tried to set any value to check if it would update before the files validation thread finishes its work.
@Override
public void update(Observable arg0, Object arg1) {
progressBar.setValue(66);
}
}
【问题讨论】:
-
您的问题是线程问题之一——您要么在 Swing 事件线程上调用长时间运行的代码,要么试图从 Swing 事件线程更改进度条的属性。可能是第一个而不是第二个,但无论哪种方式都必须修复。您必须查看您的代码并确保您正确处理 Swing 线程。查看“Swing 中的并发”并研究该系列文章以了解更多详细信息以及 JProgressBar 教程。
-
如需尽快获得更好的帮助,请发帖minimal reproducible example 或Short, Self Contained, Correct Example。
标签: java multithreading swing event-dispatch-thread jprogressbar