I would read the text file in a loop on a dedicated work thread, not the event-dispatch thread (EDT). If I know the total number of words to be read, then I can compute the percentage completed at each iteration of the loop and update the progress bar accordingly.
Sample Code
The following code puts the progress bar in indeterminate mode during preprocessing and postprocessing, displaying an animation that indicates work is occurring. Determinate mode is used when reading iteratively from the input file.
// INITIALIZATION ON EDT
// JProgressBar progress = new JProgressBar();
// progress.setStringPainted(true);
// PREPROCESSING
// update progress bar (indeterminate mode)
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
progress.setIndeterminate(true);
progress.setString("Preprocessing...");
}
});
// perform preprocessing (open input file, determine total number of words, etc)
// PROCESSING
// update progress bar (switch to determinate mode)
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
progress.setIndeterminate(false);
}
});
int count = 0;
while (true)
{
// read a word from the input file; exit loop if EOF
// compute soundex representation
// add entry to map (hash table)
// compute percentage completed
count++;
final int percent = count * 100 / total;
// update progress bar on the EDT
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
progress.setString("Processing " + percent + "%");
progress.setValue(percent);
}
});
}
// POSTPROCESSING
// update progress bar (switch to indeterminate mode)
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
progress.setIndeterminate(true);
progress.setString("Postprocessing...");
}
});
// perform postprocessing (close input file, etc)
// DONE!
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
progress.setIndeterminate(false);
progress.setString("Done!");
progress.setValue(100);
}
});
Suggestions
- Consider writing a convenience method to update the progress bar on the EDT, so as to reduce clutter in your code (
SwingUtilities.invokeLater... public void run()...
)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…