本文介绍了Java - ProgressBar 在计算后打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have main file that use ProgressBar.In main file I call ProgressBar as

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

我在调用可执行文件calculate.exe"后调用 ProgressBar 以显示 calculate.exe 现在正在运行.但是 ProgressBar 在calculate.exe"完成时打开.如何并行执行calculate.exe"和ProgressBar?我听说过 SwingWorker,但我完全不明白如何在我的应用程序中使用它.

I call ProgressBar after calling executable file "calculate.exe" to show that calculate.exe is working now. But ProgressBar opens when "calculate.exe" finished. How to make parallel executing of "calculate.exe" and ProgressBar? I hear about SwingWorker but I absolutely don't understand how to use it in my application.

我的进度条文件:

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();
}

}

提前致谢!

推荐答案

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

You can use Executors for background processes. In this case your progressBar will be working in EDT and your calculate.exe in another thread. Try this code:

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

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

            }
        });

这篇关于Java - ProgressBar 在计算后打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 16:17