0

I have a code with two methods.

public void fondo() { ... }        //Gathers JFrame Background and system time
public void recuperarDatosInternet() {...} //Connects to a URL and gets data.

When the JFrame is running, at the beginning it takes four or five seconds to perform all the operations of those methods.

While it's loading, the frame displays totally empty for 3 or 4 seconds until all the methods are complete, then the frame shows up and it's all right.

How can I make a Progress Bar that shows the user that something it's loading? I don't mean a ProgressBar that are predetermined to take "4000 ms". I am referring to a progressbar that can take whatever it takes, and the bar doesn't reach the 100% until the methods are complete.

4

2 回答 2

3

您可以为此使用SwingWorker 。此类允许在后台线程中完成耗时的工作,同时不会占用用户界面。它还具有将工作划分为“块”并在完成这些工作块时更新用户界面的功能。这是进度条所需要的,尽管它取决于您的任务是否“可分块”。上面的链接将您带到此类的 JavaDoc,其中包含简单和“分块”用法的示例。

于 2013-09-03T23:10:02.473 回答
2

如果您在The Event Dispatch Thread中运行繁重的任务,它将冻结直到完成,以避免您可以使用SwingWorker. 按照此链接查看完整示例progressBar,特别注意setProgress() publish()process()

例子:

public class MyWorker extends SwingWorker<Integer, String> {

  @Override
  protected Integer doInBackground() throws Exception {
    // Start
    publish("Start Download");
    setProgress(1);

    // More work was done
    publish("More work was done");
    setProgress(10);

    // Complete
    publish("Complete");
    setProgress(100);
    return 1;
  }

  @Override
  protected void process(List< String> chunks) {
    // Messages received from the doInBackground() (when invoking the publish() method)
  }
}

在客户端代码中:

    SwingWorker worker = new MyWorker();
    worker.addPropertyChangeListener(new MyProgressListener());
    worker.execute();

   class MyProgressListener implements PropertyChangeListener {
      @Override
      public void propertyChange(final PropertyChangeEvent event) {
        if(event.getPropertyName().equalsIgnoreCase("progress")) {
          downloadProgressBar.setIndeterminate(false);
          downloadProgressBar.setValue((Integer) event.getNewValue());
        }         
      }
     }
于 2013-09-04T02:47:56.127 回答