2010-07-06 30 views
0

我有一個程序,需要一定的時間創建PDF文件 我想展現給用戶的JProgressBar不顯示(無螺紋)

進步,當我做完了PDF文件我嘗試調用進度更新其狀態:

ProgressDialog progress = new ProgressDialog(instance, numberOfInvoices); 
progress.setVisible(true); 
progress.setAlwaysOnTop(true); 

for(int i = 0 ; i<numOfPdfs ; i++){ 
    progress.change(i + 1); 
} 

的progressdialog看起來是這樣的:

public class ProgressDialog extends JDialog { 

    private JProgressBar progressBar; 

    public ProgressDialog(Window parent, int aantal) { 
     super(parent); 

     this.setPreferredSize(new Dimension(300, 150)); 

     progressBar = new JProgressBar(0, aantal); 
     progressBar.setValue(0); 
     progressBar.setSize(new Dimension(280, 130)); 
     this.add(progressBar, BorderLayout.CENTER); 

     this.pack(); 
     this.setLocationRelativeTo(parent); 
    } 

    public void change(int aantal) { 
     if (aantal < progressBar.getMaximum() && aantal >= 0) { 
      progressBar.setValue(aantal); 
     } 
    } 
} 

我得到的是一個空的窗口(白色)

我環顧這個論壇,但胎面解決方案似乎太複雜

計算2個pdf文件之間我應該能夠更新gui,對不對?

確定科林

我想這:(完整的類)

public class ProgressDialog extends JDialog { 

    private JProgressBar progressBar; 
    private String message; 
    private static int number; 

    public ProgressDialog(Window parent, int max, String message) { 
    super(parent); 

    this.message = message; 
    this.setPreferredSize(new Dimension(300, 150)); 

    progressBar = new JProgressBar(0, max); 
    progressBar.setValue(0); 
    progressBar.setSize(new Dimension(280, 130)); 
    progressBar.setString(message + " 0/" + progressBar.getMaximum()); 
    progressBar.setStringPainted(true); 
    this.add(progressBar, BorderLayout.CENTER); 

    this.pack(); 
    this.setLocationRelativeTo(parent); 

    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); 


    } 

    public void change(int number) { 
    ProgressDialog.number = number; 
    SwingUtilities.invokeLater(new Runnable() { 

     public void run() { 
     int number = ProgressDialog.getAantal(); 
     if (number < progressBar.getMaximum() && number >= 0) { 
      progressBar.getModel().setValue(number); 
      progressBar.setString(message + " " + progressBar.getValue() + "/" + progressBar.getMaximum()); 
      System.out.println("progressbar update: " + number + "/" + progressBar.getMaximum()); 
     } else { 
      setCursor(null); 
      System.out.println("progressbar terminated"); 
     } 
     } 
    }); 
    } 

    public static int getAantal(){ 
    return number; 
    } 
} 

現在它仍顯示空窗 但是當所有的PDF文件已經準備好它確實表明與0%的進度完成 然後它關閉(像它應該這樣做)

任何想法,爲什麼它在過程中保持空白?

回答

4

你確實需要用線程來完成它。更好的學習而不是逃避,因爲它是一個常見的GUI框架設計。

它可以是簡單的:

public void change(int aantal) { 
    SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      if (aantal < progressBar.getMaximum() && aantal >= 0) { 
       progressBar.setValue(aantal); 
      } 
     } 
    }); 
} 

或用invokeAndWait()取代invokeLater()

0

請閱讀Swing教程Concurrency中的部分,瞭解爲什麼需要線程來解決此問題。另請閱讀「如何使用進度條」部分的示例。