這是我第一次必須使用進度條工作,並且我面臨一個問題,除了我試圖從它始終保持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/)。 –