我有使用ProgressBar的主文件。 在主文件中,我将ProgressBar称为
ProgressBar pbFrame = new ProgressBar();
pbFrame.setVisible(true);
我在调用可执行文件“calculate.exe”后调用ProgressBar来显示calculate.exe现在正在运行。但是当“calculate.exe”完成时,ProgressBar会打开。如何并行执行“calculate.exe”和ProgressBar?我听说过SwingWorker,但我完全不明白如何在我的应用程序中使用它。
我的ProgressBar文件:
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 :(得分: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
答案 1 :(得分:1)
您可以将执行者用于后台进程。在这种情况下,您的progressBar将在EDT中工作,您的calculate.exe将在另一个线程中工作。试试这段代码:
ProgressBar pbFrame = new ProgressBar();
pbFrame.setVisible(true);
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() {
// run background process
}
});