您好,我想在 Swing Worker 类的帮助下更新我的 JProgress Bar。我在这个论坛上搜索了关于这个主题的其他问题,并获取了一些解决方案的代码,但在我的情况下我不起作用:(我有两个类:在第一个类中,我用这个代码创建了 Swing Worker 类 BitmapFilterParralelGrey 的对象:
Greyscale.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
int numThreads = Runtime.getRuntime().availableProcessors();
int HeightPerThread = image.getHeight() / numThreads;
BitmapFilterParallelGrey[] bitmapFilter = new BitmapFilterParallelGrey[numThreads];
int startRow = 0, endRow = 0;
for (int i = 0; i < numThreads; ++i) {
startRow = i * HeightPerThread;
endRow = startRow + HeightPerThread;
bitmapFilter[i] = new BitmapFilterParallelGrey(image,
startRow, endRow);
bitmapFilter[i].addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent e) {
if ("progress".equals(e.getPropertyName())) {
BitmapViewer.ProgressBar.setIndeterminate(false);
BitmapViewer.ProgressBar.setValue((Integer) e.getNewValue());
}
}
});
bitmapFilter[i].execute();
}
for (int i = 0; i < numThreads; i++) {
try {
bitmapFilter[i].get();
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
}
showImage();
}
});
由于 SwingWorker 类中的执行应该是线程的,所以我在循环中创建了几个对象。在我的第二类 BitmapFilterParallelGrey 中,我在 doInBackground() 中过滤图像并设置 ProgressValue。编码:
public class BitmapFilterParallelGrey extends SwingWorker<Void, Void> {
BufferedImage image;
private int startRow, endRow;
public BitmapFilterParallelGrey(BufferedImage image, int startRow, int endRow){
this.image = image;
this.startRow= startRow;
this.endRow= endRow;
}
@Override
public Void doInBackground() throws Exception {
int width = image.getWidth();
for(int i=startRow; i<endRow; i++)
{
for(int j=0; j<width; j++)
{
//Filter image
}
setProgress(i/100);
Thread.sleep(10);
}
return null;
}
}
问题在于过滤完成时进度条更新(100%)。为什么它在后台过滤时不更新?谢谢!