Java progressbar feeding

后端 未结 1 1669
刺人心
刺人心 2021-01-23 18:29

I have MainProgramWindow GUI. This GUI has some variables and one button call createExcel method of Sql class and start progress bar same time.

    public class          


        
1条回答
  •  说谎
    说谎 (楼主)
    2021-01-23 18:38

    You are executing all task in the same thread The Event Dispatch Thread. A good way to solve that is executing business code in a separate thread to don't block the gui and you can update your gui without waiting your business code finish. Swing provides SwingWorker class to achieve that. Here you have a good example with a progressBar. Swing Worker Example.

    Read more How to Use Progress Bars.

    In a simple what you do is to make a swingWorker sublcass and override doInBackGround().

    Example:

      public class Worker extends SwingWorker {
    
            @Override
            protected Void doInBackground() throws Exception {
               //here you make heavy task this is running in another thread not in EDT
               int i = 0;
               setProgress(i);
               // call query 1
               while(i < 50){
                 setProgress(i++);
                 Thread.sleep(5); // random magic number
               }
               // then call query 2
               while(i <= 100){
                 setProgress(i++);
                 Thread.sleep(5); // random magic number
               }
    
               return null;
            }
        }
    

    And in your client code where you have the progressBar:

    SwingWorker myWorker = new Worker();
    myWorker.addPropertyChangeListener(new PropertyChangeListener() {
      @Override
      public void propertyChange(final PropertyChangeEvent event) {
        switch (event.getPropertyName()) {
        case "progress":
          myProgressBar.setIndeterminate(false);
          myProgressBar.setValue((Integer) event.getNewValue());
          break;
        }
     }
    });
    //then to get start you have to use execute()
    worker.execute();
    

    Here you have an example and another one

    0 讨论(0)
提交回复
热议问题