1

我有使用 ProgressBar 的主文件。在主文件中,我将 ProgressBar 称为

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

我在调用可执行文件“calculate.exe”后调用 ProgressBar 以显示 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();
}

}

提前致谢!

4

2 回答 2

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

于 2013-10-23T10:08:44.560 回答
1

您可以将Executors用于后台进程。在这种情况下,您的 progressBar 将在 EDT 中工作,而您的 calculate.exe 在另一个线程中。试试这个代码:

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

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

            }
        });
于 2013-10-23T10:57:05.640 回答