我正在尝试使用ProgressMonitor更新用户,并提供取消操作的选项。
这是我正在从HD读取图形图像的SwingWorker类。 po.getThumbNail()使用ImageIO.read(...);这很费时间。
public class BuildArray extends SwingWorker<Object[][], Void>
{
private ArrayList<PhotoObject> files;
private Object[][] array;
private ImageIcon broken;
private int row;
private int column;
public BuildArray(ArrayList<PhotoObject> files, ImageIcon broken)
{
this.files = files;
this.broken = broken;
column = PhotoObject.HEADER.length;
array = new Object[files.size()][column];
}
@Override
protected Object[][] doInBackground() throws Exception
{
row = 0;
setProgress(0);
//System.out.println("SwingWorker: " + javax.swing.SwingUtilities.isEventDispatchThread());
for (PhotoObject pO : files)
{
array[row][0] = pO.getFile();
array[row][1] = pO.getStatus();
array[row][2] = pO.getSearchWords();
if (pO.getThumbNail() == null)
array[row][3] = broken;
else
array[row][3] = new ImageIcon(pO.getThumbNail());
row++;
int current = row * 100 / files.size();
//publish(row);
setProgress(current);
if (isCancelled())
trimArray();
}
return array;
}
}
这是“ Manager”类,用于实例化SwingWorker对象,并将Object [] []返回到GUI类,该GUI类将在JTable中显示结果。 Manager会将对SwingWorker类的引用传递回GUI进行观看。
public class PhotoManager extends Thread implements IFunctions
{
private Object [][] build2DArray(ArrayList<PhotoObject> files, boolean showMonitor)
{
BuildArray buildArray = new BuildArray(files, BROKEN);
if (showMonitor)
monitor.startMonitor(buildArray, 0, files.size());
//System.out.println("PhotoManager: " + javax.swing.SwingUtilities.isEventDispatchThread());
buildArray.execute();
Object[][] array = null;
try
{
array = buildArray.get();
}
catch (InterruptedException | ExecutionException e)
{
array = buildArray.getArray();
}
return array;
}
}
这是试图显示ProgressMonitor的GUI类。
public class MainWindow extends JFrame implements ActionListener, IReDraw, PropertyChangeListener, IProgressMonitor
{
@Override
public void startMonitor(SwingWorker<Object[][], Void> sw, int min, int max)
{
swingWorker = sw;
swingWorker.addPropertyChangeListener(this);
monitor = new ProgressMonitor(this, null, "Processing...", min, max);
}
@Override
public void propertyChange(PropertyChangeEvent evt)
{
if (evt.getPropertyName().equals("progress"))
{
//int x = (Integer) evt.getNewValue();
int x = swingWorker.getProgress();
monitor.setProgress(x);
}
}
因此,当我运行此命令时,只有在doInBackground()方法完成后才调用propertyChange()方法。因此,仅在SwingWorker完成后才显示ProgressMonitor,这毫无意义。据我所知,GUI和Manager类都在EDT上运行。
我认为,我只包括了相关的方法。我一直在这里和其他站点上查看ProgressMonitor和SwingWorker的示例。我不知道为什么它对我不起作用。