这是我第一次必须使用进度条工作,并且我面临一个问题,除了我试图从它始终保持0%的地方呼叫它的setValue(x)
以及在我的方法程序完成后直接进入100%。JProgressBar不会在一个循环内实时更新
我试图做一个扩展线程的内部类,然后我试图在我的“主要”方法内启动一个新的线程,然后在最后我尝试使用观察者。这些似乎那些根据这一职位,但遗憾的是没有给我
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教程。 –
为了更好地提供帮助,请发布[MCVE]或[简短,独立,正确的示例](http://www.sscce.org/)。 –