public void start ( java . awt . Component top , String taskName , int progressMaxCount ) { // create ProgressMonitor pm = new javax . swing . ProgressMonitor ( top , taskName , "" , 0 , progressMaxCount ) ; pm . setMillisToDecideToPopup ( millisToDecideToPopup ) ; pm . setMillisToPopup ( millisToPopup ) ; // do task in a seperate, non-event, thread taskThread = new Thread ( task ) ; taskThread . start ( ) ; // create timer, whose events happen on the awt event Thread ActionListener watcher = new ActionListener ( ) { public void actionPerformed ( ActionEvent evt ) { secs ++ ; if ( pm . isCanceled ( ) ) { task . cancel ( ) ; } else { // indicate progress String note = task . getNote ( ) ; pm . setNote ( note == null ? secs + " secs" : note ) ; int progress = task . getProgress ( ) ; pm . setProgress ( progress <= 0 ? secs : progress ) ; } // need to make sure task acknowledges the cancel; so dont shut down // until the task is done if ( task . isDone ( ) ) { timer . stop ( ) ; pm . close ( ) ; // Toolkit.getDefaultToolkit().beep(); if ( task . isError ( ) ) { javax . swing . JOptionPane . showMessageDialog ( null , task . getErrorMessage ( ) ) ; } if ( task . isSuccess ( ) ) fireEvent ( new ActionEvent ( this , 0 , "success" ) ) ; else if ( task . isError ( ) ) fireEvent ( new ActionEvent ( this , 0 , "error" ) ) ; else if ( task . isCancel ( ) ) fireEvent ( new ActionEvent ( this , 0 , "cancel" ) ) ; else fireEvent ( new ActionEvent ( this , 0 , "done" ) ) ; } } } ; timer = new javax . swing . Timer ( 1000 , watcher ) ; // every second timer . start ( ) ; }
Call this from awt event thread . The task is run in a background thread .