Search code examples
javaswingjprogressbar

Simulating a long-running operation


How could I simulate a long-running database operation? My requirement is to display a dialog box with a JProgressBar until the operation is completed.


Solution

  • Use a background thread (such as one provided by a SwingWorker) to run a for loop going from 1 to 10 with a Thread.sleep inside of the loop. Then if it is a determinate mode JProgressBar, you can update its value by passing 10 * the loop index to the progress bar (taking care to do so on the Swing thread, the EDT, of course).

    Edit:
    @James Poulson: If you're using a SwingWorker object, you would use the publish/process methods and the done method to update on the EDT. If you're using your own background thread, you'd be sure to wrap any group of Swing calls in a Runnable and queue it on the EDT with invokeLater.