2013-10-23 32 views
1

我有使用ProgressBar的主文件。 在主文件我稱之爲進度爲Java - 計算後打開ProgressBar

ProgressBar pbFrame = new ProgressBar(); 
pbFrame.setVisible(true); 

我打電話叫進度可執行文件「calculate.exe」,顯示現在calculate.exe工作後。但是當「calculate.exe」完成時,ProgressBar會打開。如何使並行執行「calculate.exe」和ProgressBar?我聽說過SwingWorker,但我絕對不明白如何在我的應用程序中使用它。

我的進度文件:

public class ProgressBar extends JFrame { 

static private int BOR = 10; 
private String filename; 

public ProgressBar() { 
super("Calculating progress"); 

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

JPanel panel = new JPanel(); 
    panel.setBorder(BorderFactory.createEmptyBorder(BOR, BOR, BOR, BOR)); 
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); 

    panel.add(new JLabel("Calculating...")); 

    panel.add(Box.createVerticalGlue()); 

    JProgressBar progressBar1 = new JProgressBar(); 
    progressBar1.setIndeterminate(true);   
    panel.add(progressBar1); 

    panel.add(Box.createVerticalGlue()); 

    JPanel buttonsPanel = new JPanel(); 
    buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.Y_AXIS)); 

    buttonsPanel.add(Box.createVerticalGlue()); 

    JButton quitButton = new JButton("OK!"); 
    quitButton.setHorizontalAlignment(JButton.CENTER); 
    quitButton.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent event) { 
      dispose(); 
     } 
    }); 

    panel.add(quitButton); 

    getContentPane().setLayout(new BorderLayout()); 
    getContentPane().add(panel, BorderLayout.CENTER); 
    setPreferredSize(new Dimension(200, 110)); 
    setLocationRelativeTo(null); 
    pack(); 
} 

}

在此先感謝!

+0

_I絕對不知道如何使用it_好,我也很難理解什麼都不可能取消與理解的API文檔的例子......從這裏開始(和或在swing標籤wiki中引用的教程),嘗試根據您的上下文進行調整,然後返回一個SSCCE,該SSCCE可以證明您確切卡在哪裏 – kleopatra

回答

1

您可以使用後臺進程執行人 。在這種情況下,您的progressBar將在EDT和另一個線程中的calculate.exe中運行。試試這個代碼:

ProgressBar pbFrame = new ProgressBar(); 
pbFrame.setVisible(true);  
Executors.newSingleThreadExecutor().execute(new Runnable() { 

      @Override 
      public void run() { 
       // run background process 

      } 
     }); 
+0

非常感謝您的解答!真的行。 – Denis

1

你是對的,SwingWorker是要走的路。這是一種很難給出完整的代碼在你的問題中給出的信息,但它在這個方案的工作原理:

SwingWorker worker = new SwingWorker<MyReturnType, Void>() { 

    @Override 
    public MyReturnType doInBackground() { 
     // do your calculation and return the result. Change MyReturnType to whatever you need 
    } 

    @Override 
    public void done() { 
     // do stuff you want to do after calculation is done 
    } 
}; 

看到這裏的官方教程:http://docs.oracle.com/javase/tutorial/uiswing/concurrency/simple.html

+0

感謝您的回答,它也可以工作!但有小問題 - 進度條框打開,但百分數字符串在1-2秒內出現。爲什麼? 「calculate.exe」的工作原因是什麼? – Denis

+0

你需要自己設置進度。我不知道從Java調用exe文件。我想這比其他任何事情都要難過0%和100%的進步。 –