java中jprogressbar_java – 如何使用JProgressBar?

我会在专用工作线程的循环中读取文本文件,而不是事件派发线程(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);

}

});

建议

>考虑编写一个方便的方法来更新EDT上的进度条,以减少代码中的混乱(SwingUtilities.invokeLater … public void run()…)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值