Example usage for javax.swing SwingWorker get

List of usage examples for javax.swing SwingWorker get

Introduction

In this page you can find the example usage for javax.swing SwingWorker get.

Prototype

public final T get() throws InterruptedException, ExecutionException 

Source Link

Document

Note: calling get on the Event Dispatch Thread blocks all events, including repaints, from being processed until this SwingWorker is complete.

Usage

From source file:com.anrisoftware.prefdialog.miscswing.docks.dockingframes.core.DockingFramesDock.java

private void doLoadLayout(String name, InputStream stream, PropertyChangeListener... listeners)
        throws LayoutInterruptedException, LayoutLoadingException {
    try {//w w w  .  j a v a 2s .  com
        SwingWorker<InputStream, InputStream> worker = loadFactory.create(layoutListeners, this, name, control,
                stream);
        for (PropertyChangeListener l : listeners) {
            worker.addPropertyChangeListener(l);
        }
        worker.execute();
        worker.get();
    } catch (InterruptedException e) {
        throw new LayoutInterruptedException(name, e);
    } catch (ExecutionException e) {
        throw new LayoutLoadingException(name, e.getCause());
    }
}

From source file:com.anrisoftware.prefdialog.miscswing.docks.dockingframes.core.DockingFramesDock.java

private void doSaveLayout(String name, OutputStream stream, PropertyChangeListener... listeners)
        throws LayoutException {
    try {/*from   ww  w . j a  v a 2s  .  c o m*/
        SwingWorker<OutputStream, OutputStream> worker = saveFactory.create(layoutListeners, this, name,
                control, stream);
        for (PropertyChangeListener l : listeners) {
            worker.addPropertyChangeListener(l);
        }
        worker.execute();
        worker.get();
    } catch (ExecutionException e) {
        throw new LayoutSavingException(name, e.getCause());
    } catch (InterruptedException e) {
        throw new LayoutInterruptedException(name, e);
    }

}

From source file:com.orthancserver.DicomDecoder.java

public DicomDecoder(final OrthancConnection c, boolean isInstance, String uuid)
        throws IOException, InterruptedException, ExecutionException {
    ImageStack stack = null;//from  www .  j a  v a  2  s.  co  m
    JSONObject tags = null;
    String tagsUri, name;

    if (isInstance) {
        name = "Instance " + uuid;
        tags = (JSONObject) c.ReadJson("/instances/" + uuid + "/tags");
        stack = AddSlice(stack, c, uuid);
    } else {
        name = "Series " + uuid;

        JSONObject series = (JSONObject) c.ReadJson("/series/" + uuid);
        JSONArray instances = (JSONArray) series.get("Instances");

        try {
            tags = (JSONObject) c.ReadJson("/series/" + uuid + "/shared-tags");
        } catch (Exception e) {
            // Fallback for old versions of Orthanc, without "shared-tags"
            tags = (JSONObject) c.ReadJson("/instances/" + (String) instances.get(0) + "/tags");
        }

        final String[] slices = GetSlices(c, instances);
        final ProgressDialog progress = new ProgressDialog(slices.length);

        try {
            progress.setVisible(true);
            SwingWorker<ImageStack, Float> worker = new SwingWorker<ImageStack, Float>() {
                @Override
                protected ImageStack doInBackground() {
                    try {
                        ImageStack stack = null;

                        for (int i = 0; i < slices.length; i++) {
                            if (progress.IsCanceled()) {
                                return null;
                            }

                            progress.SetProgress(i);
                            stack = AddSlice(stack, c, slices[i]);
                        }

                        return stack;
                    } catch (IOException e) {
                        return null;
                    }
                }
            };

            worker.execute();
            stack = worker.get();
        } finally {
            progress.setVisible(false);
        }
    }

    image_ = new ImagePlus(name, stack);

    ExtractCalibration(image_, tags);
    ExtractPixelSpacing(image_, tags);
    ExtractDicomInfo(image_, tags);
}

From source file:burlov.ultracipher.swing.SwingGuiApplication.java

protected void measurePerformance() {
    SwingWorker<Double, Object> task = new SwingWorker<Double, Object>() {

        @Override//from  w w w . jav  a  2 s .c o  m
        protected Double doInBackground() throws Exception {
            Ultracipher.measurePerformance();// Warm up
            return Ultracipher.measurePerformance();
        }
    };
    WaitDialog dlg = new WaitDialog(getMainFrame(), "Measure performance", task, 0, 0);
    dlg.start();
    try {
        JOptionPane.showMessageDialog(getMainFrame(),
                String.format("Performance index (bigger is better): %.3f", task.get()));
    } catch (Exception e) {
        e.printStackTrace();
        showError(e);
    }
}

From source file:richtercloud.document.scanner.components.OCRResultPanel.java

private void startOCR() {
    String oCRResult = null;/* w  ww . j  a v  a 2 s  .c om*/
    if (!cancelable) {
        oCRResult = this.oCRResultPanelFetcher.fetch();
    } else {
        showProgressMonitor();
        final SwingWorker<String, String> oCRThread = new SwingWorker<String, String>() {
            private final OCRResultPanelFetcherProgressListener progressListener = new OCRResultPanelFetcherProgressListener() {
                @Override
                public void onProgressUpdate(OCRResultPanelFetcherProgressEvent progressEvent) {
                    int progress = (int) (progressEvent.getProgress() * 100);
                    if (progressMonitor != null) {
                        //might be null if the panel isn't displayed yet
                        progressMonitor.setProgress(progress);
                    }
                }
            };

            @Override
            public String doInBackground() {
                oCRResultPanelFetcher.addProgressListener(progressListener);
                try {
                    Thread thread1 = new Thread() {
                        @Override
                        public void run() {
                            while (!isDone()) {
                                if (progressMonitor != null && progressMonitor.isCanceled()) {
                                    oCRResultPanelFetcher.cancelFetch();
                                    break;
                                }
                                try {
                                    Thread.sleep(100);
                                } catch (InterruptedException ex) {
                                    throw new RuntimeException(ex);
                                }
                            }
                        }
                    };
                    thread1.start();
                    String retValue = oCRResultPanelFetcher.fetch();
                    return retValue;
                } catch (Exception ex) {
                    progressMonitor.setProgress(101);
                    messageHandler.handle(new Message(
                            String.format("An exception during fetching OCR result occured: %s",
                                    ExceptionUtils.getRootCauseMessage(ex)),
                            JOptionPane.ERROR_MESSAGE, "Exception occured"));
                }
                return null;
            }

            @Override
            protected void done() {
                oCRResultPanelFetcher.removeProgressListener(progressListener);
                progressMonitor.setProgress(101);
            }
        };
        oCRThread.execute();
        try {
            oCRResult = oCRThread.get();
        } catch (InterruptedException | ExecutionException ex) {
            throw new RuntimeException(ex);
        }
    }
    if (oCRResult != null) {
        //might be null if fetch has been canceled (this check is
        //unnecessary for non-cancelable processing, but don't care
        this.oCRResultTextArea.setText(oCRResult);
    }
}

From source file:richtercloud.document.scanner.gui.MainPanel.java

/**
 * Uses a modal dialog in order to display the progress of the retrieval and
 * make the operation cancelable.// w  w w . j  a  v a 2s.  co  m
 * @param documentFile
 * @return the retrieved images or {@code null} if the retrieval has been
 * canceled (in dialog)
 * @throws DocumentAddException
 * @throws InterruptedException
 * @throws ExecutionException
 */
/*
internal implementation notes:
- can't use ProgressMonitor without blocking EVT instead of a model dialog
when using SwingWorker.get
*/
public List<BufferedImage> retrieveImages(final File documentFile)
        throws DocumentAddException, InterruptedException, ExecutionException {
    if (documentFile == null) {
        throw new IllegalArgumentException("documentFile mustn't be null");
    }
    final SwingWorkerGetWaitDialog dialog = new SwingWorkerGetWaitDialog(SwingUtilities.getWindowAncestor(this), //owner
            DocumentScanner.generateApplicationWindowTitle("Wait", APP_NAME, APP_VERSION), //dialogTitle
            "Retrieving image data", //labelText
            null //progressBarText
    );
    final SwingWorker<List<BufferedImage>, Void> worker = new SwingWorker<List<BufferedImage>, Void>() {
        @Override
        protected List<BufferedImage> doInBackground() throws Exception {
            List<BufferedImage> retValue = new LinkedList<>();
            try {
                InputStream pdfInputStream = new FileInputStream(documentFile);
                PDDocument document = PDDocument.load(pdfInputStream);
                @SuppressWarnings("unchecked")
                List<PDPage> pages = document.getDocumentCatalog().getAllPages();
                for (PDPage page : pages) {
                    if (dialog.isCanceled()) {
                        document.close();
                        MainPanel.LOGGER.debug("tab generation aborted");
                        return null;
                    }
                    BufferedImage image = page.convertToImage();
                    retValue.add(image);
                }
                document.close();
            } catch (IOException ex) {
                throw new DocumentAddException(ex);
            }
            return retValue;
        }

        @Override
        protected void done() {
        }
    };
    worker.addPropertyChangeListener(new SwingWorkerCompletionWaiter(dialog));
    worker.execute();
    //the dialog will be visible until the SwingWorker is done
    dialog.setVisible(true);
    List<BufferedImage> retValue = worker.get();
    return retValue;
}

From source file:utybo.branchingstorytree.swing.OpenBST.java

/**
 * Launch OpenBST/* w  w w.  j a  va  2s.  co m*/
 *
 * @param args
 *            Arguments. The first argument is the language code to be used
 */
public static void main(final String[] args) {
    // Before we do anything, setup system properties
    // First one to ensure Java 9's scaling system gets out of the way
    System.setProperty("sun.java2d.uiScale", "1.0");
    // Second one to force hardware acceleration
    System.setProperty("sun.java2d.opengl", "true");

    LOG.info("OpenBST version " + VERSION + ", part of the BST project");
    LOG.trace("[ INIT ]");
    LOG.trace("Loading language files");
    loadLang(args.length > 0 ? args[0] : null);

    LOG.trace("Applying Look and Feel");
    OpenBSTGUI.initializeLaF();
    VisualsUtils.fixTextFontScaling();

    LOG.trace("Loading scaling factor");
    Icons.loadScalingFactor();

    Splashscreen sc = Splashscreen.start();
    SwingWorker<Void, String> sw = new SwingWorker<Void, String>() {

        @Override
        protected Void doInBackground() {
            LOG.trace("Initializing JavaFX");
            publish(Lang.get("splash.init"));
            // Necessary - because we are killing Scenes all the time with WebViews in NodePanels,
            // JFX may think we just ended our application.
            // OpenBST exits with a dirty System.exit() anyway.
            Platform.setImplicitExit(false);
            // Initialize JavaFX
            new JFXPanel();
            VisualsUtils.invokeJfxAndWait(() -> {
                // Initialize the web engine
                new WebEngine();
                // Initialize a view
                new WebView();
            });

            LOG.info("Loading icons...");
            publish(Lang.get("splash.icons"));
            long timeAtIconStart = System.currentTimeMillis();
            Icons.load();
            LOG.info("Time taken to load icons : " + (System.currentTimeMillis() - timeAtIconStart) + " ms");

            LOG.info("Loading backgrounds...");
            publish(Lang.get("splash.loadbg"));
            Icons.loadBackgrounds();

            // $EXPERIMENTAL
            LOG.info("Caching backgrounds...");
            publish(Lang.get("splash.processbg"));
            IMGClient.initInternal();

            // $EXPERIMENTAL
            LOG.info("Loading internal BTS files...");
            publish(Lang.get("splash.loadinternalbst"));
            loadInternalBSTFiles();

            return null;
        }

        @Override
        protected void process(List<String> chunks) {
            String s = chunks.get(chunks.size() - 1);
            sc.setText(s);
        }

    };

    sw.execute();
    try {
        sw.get();
    } catch (InterruptedException | ExecutionException e1) {
        OpenBST.LOG.error(e1);
    }

    VisualsUtils.invokeSwingAndWait(() -> {
        sc.setText(Lang.get("splash.launch"));
        sc.lock();
        sc.stop();
    });
    LOG.trace("Launching app...");
    OpenBSTGUI.launch();

    VisualsUtils.invokeSwingAndWait(() -> sc.dispose());

    LOG.trace("Checking versions...");
    if (!"<unknown version>".equals(VERSION)) {
        SwingWorker<UpdateInfo, Void> worker = new SwingWorker<UpdateInfo, Void>() {

            @Override
            protected UpdateInfo doInBackground() throws Exception {
                URL updateInfoSite = new URL("https://utybo.github.io/BST/version.json");
                UpdateInfo info = new Gson().fromJson(
                        new InputStreamReader(updateInfoSite.openStream(), StandardCharsets.UTF_8),
                        UpdateInfo.class);
                return info;
            }

            @Override
            protected void done() {
                try {
                    UpdateInfo remoteVersion = this.get();
                    ComparableVersion remoteUnstable = new ComparableVersion(remoteVersion.unstable),
                            remoteStable = new ComparableVersion(remoteVersion.stable);
                    ComparableVersion local = new ComparableVersion(VERSION.substring(0, VERSION.length() - 1));

                    if (VERSION.endsWith("u")) {
                        // Local version is unstable
                        // Show updates to either the most recent unstable or the most recent stable
                        if (local.compareTo(remoteStable) < 0 && remoteStable.compareTo(remoteUnstable) < 0) {
                            // local (unstable) < stable < unstable
                            // Give options for both unstable and stable
                            JButton stablebtn = new JButton(Lang.get("up.moreinfostable"));
                            stablebtn.addActionListener(e -> {
                                VisualsUtils.browse(remoteVersion.stableurl);
                            });
                            JButton unstablebtn = new JButton(Lang.get("up.moreinfounstable"));
                            unstablebtn.addActionListener(e -> {
                                VisualsUtils.browse(remoteVersion.unstableurl);
                            });
                            OpenBSTGUI.getInstance()
                                    .addBanner(new JBannerPanel(
                                            new ImageIcon(Icons.getImage("Installing Updates", 48)),
                                            new Color(142, 255, 159), Lang.get("up.message1"), stablebtn, false,
                                            unstablebtn));
                        } else if (remoteStable.compareTo(local) < 0 && local.compareTo(remoteUnstable) < 0) {
                            // stable < local (unstable) < unstable
                            JButton unstablebtn = new JButton(Lang.get("up.moreinfo"));
                            unstablebtn.addActionListener(e -> {
                                VisualsUtils.browse(remoteVersion.unstableurl);
                            });
                            OpenBSTGUI.getInstance().addBanner(new JBannerPanel(
                                    new ImageIcon(Icons.getImage("Installing Updates", 48)),
                                    new Color(142, 255, 159), Lang.get("up.message2"), unstablebtn, false));
                        } else if (remoteUnstable.compareTo(remoteStable) < 0
                                && local.compareTo(remoteStable) < 0) {
                            // local (unstable) < stable
                            // and unstable < stable
                            JButton stablebtn = new JButton(Lang.get("up.moreinfo"));
                            stablebtn.addActionListener(e -> {
                                VisualsUtils.browse(remoteVersion.stableurl);
                            });
                            OpenBSTGUI.getInstance().addBanner(new JBannerPanel(
                                    new ImageIcon(Icons.getImage("Installing Updates", 48)),
                                    new Color(142, 255, 159), Lang.get("up.message3"), stablebtn, false));
                        }
                    } else {
                        // If we're not running an unstable version, the only interesting case is local < stable
                        if (local.compareTo(remoteStable) < 0) {
                            // local (stable) < stable
                            JButton stablebtn = new JButton(Lang.get("up.moreinfo"));
                            stablebtn.addActionListener(e -> {
                                VisualsUtils.browse(remoteVersion.stableurl);
                            });
                            OpenBSTGUI.getInstance().addBanner(new JBannerPanel(
                                    new ImageIcon(Icons.getImage("Installing Updates", 48)),
                                    new Color(142, 255, 159), Lang.get("up.message4"), stablebtn, false));
                        }
                    }
                }

                catch (InterruptedException | ExecutionException e) {
                    LOG.warn("Failed to read update information", e);
                    JButton showDetails = new JButton(Lang.get("up.showdetails"));
                    showDetails.addActionListener(ev -> Messagers.showException(OpenBSTGUI.getInstance(),
                            Lang.get("up.failedmessage"), e));
                    OpenBSTGUI.getInstance()
                            .addBanner(new JBannerPanel(new ImageIcon(Icons.getImage("Cancel", 16)),
                                    new Color(255, 144, 144), Lang.get("up.failedbanner"), showDetails, false));
                }
            }
        };
        worker.execute();
    }
}