当我调用doInBackground()时,进度监视器不显示,并且edt也会堆叠。任何可以帮助我的人都会非常感激。
mainFrame正在edt上运行,但是在另一个类中创建。
public void serializeAlbumsList(DefaultListModel<Album> albums) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
progressMonitor = new ProgressMonitor(mainFrame, "Please wait while saving your albums...", null, 0, 100);
}
});
Serializer serializer = new Serializer(albums);
try {
serializer.doInBackground();
} catch (Exception e) {
e.printStackTrace();
}
}
private class Serializer extends SwingWorker<Void, Void> implements PropertyChangeListener{
int progress;
private DefaultListModel<Album> albums;
public Serializer(DefaultListModel<Album> albums) {
this.albums = albums;
}
@Override
protected Void doInBackground() throws Exception {
setProgress(0);
for (int i = 0; i < albums.size(); i++) {
ObjectOutputStream os;
try {
FileOutputStream fs = new FileOutputStream("Album" + i + ".ser");
os = new ObjectOutputStream(fs);
os.writeObject(albums.getElementAt(i));
os.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
progress = i*(100/albums.size());
setProgress(progress);
}
return null;
}
@Override
public void propertyChange(PropertyChangeEvent e) {
if (progressMonitor.isCanceled()) {
cancel(true);
} else if ("progress" == e.getPropertyName()) {
int progress = ((Integer) e.getNewValue()).intValue();
progressMonitor.setProgress(progress);
}
}
}