2014-03-06 59 views
0

我有一个需要被GUI调用的大程序。在用户按下开始按钮之后,GUI具有需要更新的进度条(例如5%... 10%)。 问题是执行的后台任务没有固定的执行时间。因此,在某种程度上可以测量在doInBackground()方法中执行的任务的进度(我正在尝试使用SwingWorker)。或者我应该去一个不确定的进度条。 我无法清楚地理解Oracle教程页面上提供的示例,但无法找到解释如何使用进度栏的体面的页面。 任何帮助将不胜感激。更新进度条

+0

http://stackoverflow.com/questions/277007/how-to-use -jprogressbar与你的问题非常相似。 – MemLeak

+0

请发布您的代码 – Benjamin

+0

@MemLeak我的程序的输入没有固定的大小,因此执行时间会有所不同。该程序使用遗传算法,并使用线程实现。 – Sashank

回答

1

根据问题,我会用一个无限进度条

public class Indeterminate extends JProgressBar { 

    private static final long serialVersionUID = -281761375041347893L; 

    /*** 
    * initial the ProgressBar 
    */ 
    public IndeterminateProgressBar() { 
     super(); 
     setIndeterminate(true); 
     EventQueue.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       setVisible(false); 
      } 
     }); 
    } 

    /** 
    * call this, if you start a long action 
    */ 
    public void start() { 
     EventQueue.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       setVisible(true); 
      } 
     }); 
    } 

    /** 
    * if you have finished, call this 
    */ 
    public void end() { 
     EventQueue.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       setVisible(false); 
      } 
     }); 
    } 

} 

像这样来使用:

ActionListener startButtonListener = new ActionListener() { 

    @Override 
    public void actionPerformed(ActionEvent e) { 

     new Thread(new Runnable() { 

      @Override 
      public void run() { 

       try { 
        progressBar.start(); 
        // long operation 

       } catch (Exception e) { 
        // handle excpetion 
       } finally { 
        progressBar.end(); 

       } 

      } 
     }).start(); 

    } 
}; 
+0

中使用“public void propertyChange(PropertyChangeEvent evt)”方法。谢谢你回复我会试试这个。 – Sashank