【发布时间】:2013-06-09 23:21:07
【问题描述】:
我知道这里有很多JProgressBar 问题,但是通过所有答案,我似乎无法诊断出我的问题。我正在使用一些地址验证软件处理文件。我单击处理按钮,我需要我的JProgressBar 来更新每个处理的文件。
这是按钮:
private JButton getJButton0() {
...
jButton0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
jButton0ActionActionPerformed(event);
t.start();
}
...
根据大家的建议,我在一个线程中使用了setValue() 方法
Thread t = new Thread(){
public void run() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
jProgressBar0.setValue(BulkProcessor.getPercentComplete());
}
});
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
...
BulkProcessor.getPercentComplete() 是我从另一个类调用的方法,它代表完成百分比。我已经测试了这个方法,它可以正确更新。问题是进度条在文件完成处理之前不会更新,然后会跳转到 100%。如果这是一个重复的问题,我深表歉意,但我在这个网站上做了一些认真的挖掘,但没有运气。非常感谢任何帮助。
编辑:
每个推荐的副本,我都试过这个:
public void update(){
new SwingWorker<Void,Void>() {
protected Void doInBackground() throws Exception {
jProgressBar0.setValue(BulkProcessor.getPercentComplete());
return null;
};
}.execute();
}
然后尝试在actionPerformed() 下调用这个update() 方法(将t.start() 与update() 切换)。我仍然有同样的问题。
编辑
根据 user1676075 的建议,但同样的问题:
public static void update(){
new SwingWorker<Void,Integer>() {
protected Void doInBackground() throws Exception {
do
{
percentComplete = BulkProcessor.getPercentComplete();
publish(percentComplete);
Thread.sleep(100);
} while(percentComplete < 100);
return null;
}
@Override
protected
void process(List<Integer> progress)
{
jProgressBar0.setValue(progress.get(0));
}
}.execute();
}
编辑
这是我的 BulkProcessor 类的代码
private String getOutputLine( String searchString, String inputLine )
throws QasException
{
..(code for processing lines)..
countRecord++;
percentComplete = (int) Math.round((countRecord/totalRecord)*100);
totalRecord 在我的BulkProcessor 类的主类中更新
public static void main( String input, String output ){
count.clear();
try{
String inputFile = input;
String outputFile = output;
LineNumberReader lnr = new LineNumberReader(new FileReader(new File(input)));
lnr.skip(Long.MAX_VALUE);
totalRecord = lnr.getLineNumber() + 1; //line count in file
BulkProcessor bulk = new BulkProcessor(inputFile, outputFile, ConfigManager.DFLT_NAME);
bulk.process();
}catch(Exception e ){
e.printStackTrace();
}
}
【问题讨论】:
-
不要阻塞 EDT(事件调度线程)——当这种情况发生时,GUI 将“冻结”。而不是调用
Thread.sleep(n)实现 SwingTimer用于重复任务或SwingWorker用于长时间运行的任务。有关详细信息,请参阅Concurrency in Swing。 ..好的,这是我根据标题发表的评论。但是..Thread.sleep(100);里面SwingWorker?那是拟人化的怪异!为了尽快获得更好的帮助,请发帖SSCCE。 -
这是duplicate。
-
请参阅上面的编辑,我基于 Uwe Plonus 的重复链接
-
for example,有些在JTable标签下,有SwingWoker和Runnable@Thread的例子
-
不同的类只要线程正确交互就不是问题
标签: java swing swingworker event-dispatch-thread jprogressbar