进度条与函数同时运行(在另一个类中)

我创建了一个表单,其中有两个组件,按钮和进度条(Netbeans拖放).Form包含我的应用程序启动的主要方法。我已经创建了另一个类,我已经编写了一个函数。我是什么希望是当我按下一个按钮时,应用程序进入该function,并且进度条与它同时运行,当该function完成其function时,进度条显示100%完成。现在这个function可以随时完成,所以我无法设置进度条的最大值。那么,在这种情况下该怎么办?任何人都可以给我一个很好的例子。

JProgressBar.setIndeterminate(true)

既然你在所谓的“被调用的函数”里面做了什么样的工作,那么很难说,你想要的在场景中,尽管你可以把你的行像progressBar.setValue(someProgress); 定期将它的Indeterminate Statetrue ,在函数结束时你可以简单地说progressBar.setValue(100); 并且Indeterminate State将在此处变为false ,以便它可以向最终用户显示。

看看这个示例程序:

 import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ProgressExample { public static JProgressBar progressBar; private void createAndDisplayGUI() { JFrame frame = new JFrame("Progress Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationByPlatform(true); JPanel contentPane = new JPanel(); contentPane.setLayout(new BorderLayout(5, 5)); progressBar = new JProgressBar(0, 100); progressBar.setValue(0); JButton button = new JButton("START"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { progressBar.setIndeterminate(true); WorkingDialog wd = new WorkingDialog(); wd.createAndDisplayDialog(); } }); contentPane.add(progressBar, BorderLayout.PAGE_START); contentPane.add(button, BorderLayout.PAGE_END); frame.setContentPane(contentPane); frame.pack(); frame.setVisible(true); } public static void main(String... args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new ProgressExample().createAndDisplayGUI(); } }); } } class WorkingDialog extends JDialog { private String message = "HelloWorld"; private int count = 0; private JTextField tfield; private Timer timer; private ActionListener timerAction = new ActionListener() { public void actionPerformed(ActionEvent ae) { if (count == 10) { timer.stop(); ProgressExample.progressBar.setIndeterminate(false); ProgressExample.progressBar.setValue(100); ProgressExample.progressBar.setStringPainted(true); dispose(); return; } tfield.setText(tfield.getText() + message.charAt(count)); count++; } }; public void createAndDisplayDialog() { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setLocationByPlatform(true); JPanel panel = new JPanel(); tfield = new JTextField(10); panel.add(tfield); add(panel); pack(); setVisible(true); timer = new Timer(1000, timerAction); timer.start(); } } 

所以,好像你在写

 ProgressExample.progressBar.setIndeterminate(false); ProgressExample.progressBar.setValue(100); ProgressExample.progressBar.setStringPainted(true); 

在你的while循环之后。

您可以在之前的SO问题中查看我的答案 ,其中包含使用JProgressBar的示例,该示例使用SwingWorker从另一个Thread获取更新。 是否使用SwingWorker取决于您的用例。 如果函数需要一些时间来运行,则最好使用SwingWorker来避免阻止UI。