我需要从一个文本文件加载一堆单词(大约70,000个),将其添加到一个哈希表中(使用soundex作为键),并对这些值进行排序。在执行所有这些操作时,我希望使用JProgressBar显示一个进度条。像this和this这样的文章,只给出了一个非真实的例子( while循环)。有没有人能建议我该怎么做。如何从上面的条件中获取一个数字来设置进度条的值?此外,似乎有不同的方法来做这件事-使用线程,计时器等。哪种方法可能是最好的方法,如上述情况?
发布于 2008-11-10 04:18:32
我会在一个专用的工作线程上的循环中读取文本文件,而不是事件分派线程(EDT)。如果我知道要读取的总字数,那么我可以计算每次循环迭代完成的百分比,并相应地更新进度条。
示例代码
下面的代码在预处理和后处理期间将进度条置于不确定模式,并显示指示正在进行工作的动画。当迭代地从输入文件读取时,使用确定模式。
// 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);
}
});建议
为了减少代码(SwingUtilities.invokeLater... public void run()...)中的混乱,
发布于 2009-02-20 10:30:26
使用SwingWorker:http://java.sun.com/docs/books/tutorial/uiswing/concurrency/interim.html
发布于 2010-11-20 03:41:44
获取文件大小并计算每次迭代处理的字节数。这样,您就不必遍历该文件两次。
https://stackoverflow.com/questions/277007
复制相似问题