If the SwingWorker task is canceled, as I know, when the aborted method is completed

If the SwingWorker task SwingWorker canceled, how do you know when the aborted method has completed.

I have simplified the code. FixSongsController.start() running in the background. When it is completed, a report is created, and when it is done, the report will be displayed using the done() method.

An execution dialog occurs, and if the user selects cancellation (while FixSongsController.start() is running), then he calls cancel(true) on SwingWorker , causing the interrupt to be sent to FixSongsController.start() . The problem is that as soon as it is sent, it calls createReport().

I do not want to start creating a report until FixSongsController.start() finishes. I do not see how to determine when this happened.

If I remove the createReport code from FixSongsDialog and isCancelled() checks Fix Songs, the problem is worse, because then FixSongsDialog tries to display the report before creating it.

I thought I could use SwingWorker.getState() , but after calling cancelTask doInBackground() task aborts and ends shortly after the FixSongsController method is still removed.

Then I thought that I could use SwingWorker.setProgress() in the SwingWorker.setProgress() method in my finally block and add a listener that will only call showReport after changing the progress value, but setProgress is protected, so I cannot access it outside the class FixSongs .

SwingWorker Class

 public class FixSongs extends SwingWorker<String, Object> { @Override public String doInBackground() throws Exception { try { new FixSongsController().start(); if (!isCancelled()) { new FixSongsReportCreator().createReport(); } return ""; } catch (Throwable ex) { MainWindow.logger.log(Level.SEVERE, ex.getMessage(), ex); throw ex; } } @Override protected void done() { SongKong.mainWindow.dialog.close(); if (!isCancelled()) { ShowCounters showCounters = new ShowReport(); } } } 

Dialog Progress Class

 public class FixSongsDialog extends RecordBasedProgressDialog { .... @Override public void cancelTask() { try { swingWorker.cancel(true); CreateReport createReport = new CreateReport(); createReport.execute(); this.dispose(); } catch(Exception ex) { MainWindow.logger.log(Level.SEVERE,ex.getMessage(),ex); throw ex; } } class CreateReport extends SwingWorker<String, Object> { @Override public String doInBackground() throws Exception { try { new FixSongsReportCreator().createReport(); return ""; } catch(Exception ex) { MainWindow.logger.log(Level.SEVERE,ex.getMessage(),ex); throw ex; } } @Override protected void done() { ShowCounters showCounters = new ShowReport(); } } } 
+5
source share

Source: https://habr.com/ru/post/1268843/


All Articles