Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The closest thing to a standard, or ready-made way of doing this is the <code>progress</code> property and/or the publish/process method pair provided by <code>SwingWorker</code>. You can set this to a "I'm finished" value at the end of the method to indicate the background work is done. The thread waiting on the swing worker can put up a "Canceling..." message and periodically check the progress to see if it has reached completion. If the waiting thread is the swing EDT, then you will need to use a Timer to periodically check the progress property and clear the cancel message when done.</p> <p>Here's some example code that runs a stubborn background thread, which is canceled, and then waits until the progress reaches 100.</p> <pre><code>@Test public void testSwingWorker() { SwingWorker worker = new SwingWorker() { @Override protected void process(List chunks) { for (Object chunk : chunks) { System.out.println("process: "+chunk.toString()); } } @Override protected void done() { System.out.println("done"); } @Override protected Object doInBackground() throws Exception { // simulate long running method for (int i=0; i&lt;1000000000; i++) { double d = Math.sqrt(i); } System.err.println("finished"); publish("finished"); setProgress(100); return null; } }; Thread t = new Thread(worker); t.start(); try { worker.get(1, TimeUnit.SECONDS); } catch (InterruptedException e) { } catch (ExecutionException e) { } catch (TimeoutException e) { } worker.cancel(true); // now wait for finish. int progress = 0; do { try { Thread.sleep(1000); } catch (InterruptedException e) { } progress = worker.getProgress(); System.out.println(String.format("progress %d", progress)); } while (progress&lt;100); } </code></pre> <p>An alternative approach is to use the <code>publish\process</code> method pairs to push a special value indicating that the background thread has finished into the EDT. Your <code>process</code> override method in SwingWorker then picks up this special value and hides the "Canceling..." message. The advantage with this is that no polling or timers are needed. The example code shows that although <code>done</code> is called as soon as the task is canceled, the publish/process method pairs still work even when the task is cancelled.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload