Example usage for javax.swing SwingWorker SwingWorker

List of usage examples for javax.swing SwingWorker SwingWorker

Introduction

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

Prototype

public SwingWorker() 

Source Link

Document

Constructs this SwingWorker .

Usage

From source file:jshm.gui.GuiUtil.java

public static void openImageOrBrowser(final Frame owner, final String urlStr) {
    new SwingWorker<Void, Void>() {
        private BufferedImage image = null;
        private Throwable t = null;
        private boolean canceled = false;

        protected Void doInBackground() throws Exception {
            ProgressMonitor progress = null;

            try {
                // try to see if it's an image before downloading the
                // whole thing
                GetMethod method = new GetMethod(urlStr);
                Client.getHttpClient().executeMethod(method);
                Header h = method.getResponseHeader("Content-type");

                if (null != h && h.getValue().toLowerCase().startsWith("image/")) {
                    //                  jshm.util.TestTimer.start();
                    ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(owner, "Loading image...",
                            method.getResponseBodyAsStream());
                    progress = pmis.getProgressMonitor();
                    //                  System.out.println("BEFORE max: " + progress.getMaximum());
                    h = method.getResponseHeader("Content-length");

                    if (null != h) {
                        try {
                            progress.setMaximum(Integer.parseInt(h.getValue()));
                        } catch (NumberFormatException e) {
                        }/*from  w  w w .j  av  a2s. co m*/
                    }
                    //                  System.out.println("AFTER max: " + progress.getMaximum());

                    progress.setMillisToDecideToPopup(250);
                    progress.setMillisToPopup(1000);

                    image = javax.imageio.ImageIO.read(pmis);
                    pmis.close();
                    //                  jshm.util.TestTimer.stop();
                    //                  jshm.util.TestTimer.start();
                    image = GraphicsUtilities.toCompatibleImage(image);
                    //                  jshm.util.TestTimer.stop();
                }

                method.releaseConnection();
            } catch (OutOfMemoryError e) {
                LOG.log(Level.WARNING, "OutOfMemoryError trying to load image", e);
                image = null; // make it open in browser
            } catch (Throwable e) {
                if (null != progress && progress.isCanceled()) {
                    canceled = true;
                } else {
                    t = e;
                }
            }

            return null;
        }

        public void done() {
            if (canceled)
                return;

            if (null == image) {
                if (null == t) {
                    // no error, just the url wasn't an image, so launch the browser
                    Util.openURL(urlStr);
                } else {
                    LOG.log(Level.WARNING, "Error opening image URL", t);
                    ErrorInfo ei = new ErrorInfo("Error", "Error opening image URL", null, null, t, null, null);
                    JXErrorPane.showDialog(owner, ei);
                }
            } else {
                SpInfoViewer viewer = new SpInfoViewer();
                viewer.setTitle(urlStr);
                viewer.setImage(image, true);
                viewer.setLocationRelativeTo(owner);
                viewer.setVisible(true);
            }
        }
    }.execute();
}

From source file:gda.gui.BatonPanel.java

void startMonitoringServer() {
    Thread batonMonitor = ThreadManager.getThread(new Runnable() {
        @Override//from  w  ww.  j  a  v a 2  s.co  m
        public void run() {

            final long timeoutInMilliseconds = (long) (closeDownOnBatonRenewTimeoutTimeMinutes * 60 * 1000);
            final long closedownTimeoutInMilliseconds = (long) (closeDownOnBatonRenewUserPromptTimeMinutes * 60
                    * 1000);

            // Pretend the last baton renew request was received now.
            batonRenewRequestReceived = System.currentTimeMillis();

            try {
                while (keepMonitoringServer) {

                    Thread.sleep(1000);

                    final long timeSinceRenewRequest = System.currentTimeMillis() - batonRenewRequestReceived;
                    final long timeSinceUserCancelledShutdown = System.currentTimeMillis()
                            - userCancelledShutdown;
                    final long timeSinceLastEvent = Math.min(timeSinceRenewRequest,
                            timeSinceUserCancelledShutdown);

                    if (timeSinceLastEvent >= timeoutInMilliseconds) {

                        // Use invokeAndWait so that the monitoring doesn't continue until the dialog closes
                        SwingUtilities.invokeAndWait(new Runnable() {
                            @Override
                            public void run() {
                                SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

                                    @Override
                                    protected Void doInBackground() throws Exception {
                                        Thread.sleep(closedownTimeoutInMilliseconds);
                                        return null;
                                    }

                                    @Override
                                    protected void done() {
                                        if (isCancelled()) {
                                            userCancelledShutdown = System.currentTimeMillis();
                                        } else {
                                            logger.info(
                                                    "Client closing down due to lack of baton renew requests from the server which is assumed to be dead");
                                            AcquisitionFrame.instance.exit();
                                            keepMonitoringServer = false;
                                        }
                                    }

                                };
                                SwingWorkerProgressDialog dlg = new SwingWorkerProgressDialog(worker, null,
                                        "GDA Shutdown",
                                        "GDA Client has lost connection with the server. It will shut down unless you press cancel...",
                                        true, null, null);
                                dlg.execute();
                            }

                        });
                    }
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }, "BatonRequestMonitor");
    batonMonitor.start();
}

From source file:es.emergya.ui.gis.ControlPanel.java

@Override
public void actionPerformed(ActionEvent e) {
    if (centerSw != null && !centerSw.isDone() && !centerSw.isCancelled()) {
        centerSw.cancel(true);/*from w w  w.ja v  a2 s.  c o m*/
    }
    centerSw = new SwingWorker<Object, Object>() {
        @Override
        protected Object doInBackground() throws Exception {

            if (centerOptions.getSelectedItem().equals(i18n.getString("map.location"))) { // Estamos
                // centrando
                // en
                // x,
                // y
                double x = 0, y = 0;
                try {
                    x = Double.parseDouble(cx.getText().replace(',', '.'));
                    y = Double.parseDouble(cy.getText().replace(',', '.'));
                } catch (NumberFormatException nfe) {
                    log.debug("No se centra: formato erroneo");
                    return null;
                }

                String format = LogicConstants.get("FORMATO_COORDENADAS_MAPA", "UTM");
                if (format.equals(LogicConstants.COORD_UTM)) {
                    UTM u = new UTM(LogicConstants.getInt("ZONA_UTM"));
                    LatLon ll = u.eastNorth2latlon(new EastNorth(x, y));
                    view.zoomTo(Main.proj.latlon2eastNorth(ll), view.getScale());
                } else {
                    // en el latlong la x y la y van al reves
                    view.zoomTo(Main.proj.latlon2eastNorth(new LatLon(x, y)), view.getScale());
                }
            } else if (centerOptions.getSelectedItem().equals(i18n.getString("map.street"))) {
                Routing r = RoutingConsultas.find(street.getText());
                if (r != null && r.getGeometria() != null) {
                    Point center = r.getGeometria().getCentroid().getCentroid();
                    view.zoomTo(Main.proj.latlon2eastNorth(new LatLon(center.getY(), center.getX())),
                            view.getScale());
                }

            } else if (centerOptions.getSelectedItem().equals(i18n.getString("map.incidence"))) {

                final Object incidencia = incidences.getSelectedItem();
                if (incidencia == null) {
                    return null;
                }

                Incidencia i = null;
                if (incidencia instanceof Incidencia) {
                    i = (Incidencia) incidencia;
                } else {
                    i = IncidenciaConsultas.find(incidencia.toString());
                }

                Geometry geom = i.getGeometria();
                if (geom == null) {
                    return null;
                }

                Point center = geom.getCentroid();
                view.zoomTo(Main.proj.latlon2eastNorth(new LatLon(center.getY(), center.getX())),
                        view.getScale());
                return null;

            } else if (centerOptions.getSelectedItem().equals(i18n.getString("map.resource"))) {
                final Object selectedItem = resources.getSelectedItem();
                if (selectedItem == null) {
                    return null;
                }
                if (selectedItem instanceof Recurso) {
                    Recurso r = (Recurso) selectedItem;
                    HistoricoGPS h = null;
                    if (r.getId() != null) {
                        h = HistoricoGPSConsultas.lastGPSForRecurso(r);
                    } else
                        try {
                            h = r.getHistoricoGps();
                        } catch (Throwable t) {
                            h = null;
                        }
                    if (h == null) {
                        return null;
                    }
                    view.zoomTo(Main.proj.latlon2eastNorth(new LatLon(h.getPosY(), h.getPosX())),
                            view.getScale());
                } else if (selectedItem instanceof String) {
                    String r = (String) selectedItem;
                    HistoricoGPS h = HistoricoGPSConsultas.lastGPSForRecurso(r);
                    if (h == null) {
                        return null;
                    }
                    view.zoomTo(Main.proj.latlon2eastNorth(new LatLon(h.getPosY(), h.getPosX())),
                            view.getScale());
                } else if (selectedItem instanceof GpxLayer) {
                    MyGpxLayer r = (MyGpxLayer) selectedItem;
                    if (r == null || r.getLatLon() == null) {
                        return null;
                    }

                    view.zoomTo(Main.proj.latlon2eastNorth(r.getLatLon()), view.getScale());
                }
            }
            return null;
        }
    };
    centerSw.execute();

}

From source file:com.mirth.connect.manager.ManagerController.java

public void restartMirthWorker() {
    PlatformUI.MANAGER_DIALOG.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    setEnabledOptions(false, false, false, false);

    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        private String errorMessage = null;

        public Void doInBackground() {
            errorMessage = restartMirth();
            return null;
        }/*from   w w w .  j  av a2 s  . co  m*/

        public void done() {
            if (errorMessage == null) {
                PlatformUI.MANAGER_TRAY.alertInfo("The Mirth Connect Service was restarted successfully.");
            } else {
                PlatformUI.MANAGER_TRAY.alertError(errorMessage);
            }

            updateMirthServiceStatus();
            PlatformUI.MANAGER_DIALOG.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        }
    };

    worker.execute();
}

From source file:com.mirth.connect.plugins.datapruner.DataPrunerPanel.java

public void doStop() {
    setStopTaskVisible(false);//from www .  j av  a  2s .  co  m
    final String workingId = parent.startWorking("Stopping the data pruner...");

    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        @Override
        protected Void doInBackground() {
            try {
                parent.mirthClient.getServlet(DataPrunerServletInterface.class).stop();
            } catch (Exception e) {
                parent.alertThrowable(parent, e, "An error occurred while attempting to stop the data pruner.");
                return null;
            }

            return null;
        }

        @Override
        public void done() {
            parent.stopWorking(workingId);
            updateStatus();
        }
    };

    worker.execute();
}

From source file:GUI.ListOfOffres1.java

static void openListOfOffresFrame() throws IOException {

    new SwingWorker<Void, Void>() {
        @Override//from  w  w  w .j  a  v a 2s .  c  o m
        protected Void doInBackground() throws Exception {

            // do some processing here while the progress bar is running
            f.setSize(500, 500);
            f.setLocation(300, 200);
            f.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
            f.setLayout(new GridLayout(1, 1, 5, 5));
            try {
                f3.add(createListOfOffresPanel(0, "", 0));
                f.add(f3);
            } catch (IOException ex) {
                Logger.getLogger(ListOfOffres1.class.getName()).log(Level.SEVERE, null, ex);
            }

            return null;
        }

        // this is called when doInBackground finished
        @Override
        protected void done() {
            //Background processing done
            //Crate new Frale and confagurated
            ListOfOffresFrame = new JFrame();
            ListOfOffresFrame.setMaximizedBounds(null);
            ListOfOffresFrame.setMinimumSize(new Dimension(300, 400));
            ListOfOffresFrame.setTitle("Offre");
            ListOfOffresFrame.setLayout(new GridLayout(1, 1, 20, 20));
            Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
            ListOfOffresFrame.setLocation((dim.height / 2) + 150, 150);
            ListOfOffresFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            ListOfOffresFrame.add(f);
            ListOfOffresFrame.setPreferredSize(dim);
            ListOfOffresFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
            ListOfOffresFrame.setVisible(true);
            prog.setVisible(false);
        }
    }.execute();
}

From source file:com.cch.aj.entryrecorder.frame.SearchJFrame.java

private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
    BusyJFrame bf = new BusyJFrame();
    bf.setVisible(true);//from w  w  w  .j a  v a2s  .  c o  m
    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

        @Override
        protected Void doInBackground() throws Exception {
            List<Entry> list = entrySearchService.Search(txtShift.getText(), txtProduct.getText(),
                    txtBatch.getText());
            DefaultTableModel model = (DefaultTableModel) tblSearch.getModel();
            model.setRowCount(0);
            for (Entry entry : list) {
                model.addRow(new Object[] { entry.getId(), entry.getShift(), entry.getProductId().getCode(),
                        (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(entry.getCreateDate()) });
            }
            return null;
        }

        @Override
        protected void done() {
            bf.setVisible(false);
        }
    };
    worker.execute();

}

From source file:com.mirth.connect.client.ui.SettingsPanelAdministrator.java

public boolean doSave() {
    if (dashboardRefreshIntervalField.getText().length() == 0) {
        getFrame().alertWarning(this, "Please enter a valid interval time.");
        return false;
    }// w  ww  .  java  2s  . c om
    if (messageBrowserPageSizeField.getText().length() == 0) {
        getFrame().alertWarning(this, "Please enter a valid message browser page size.");
        return false;
    }
    if (eventBrowserPageSizeField.getText().length() == 0) {
        getFrame().alertWarning(this, "Please enter a valid event browser page size.");
        return false;
    }

    if (autoCompleteDelayField.isEnabled() && StringUtils.isBlank(autoCompleteDelayField.getText())) {
        getFrame().alertWarning(this, "Please enter a valid auto-complete activation delay.");
        return false;
    }

    int interval = Integer.parseInt(dashboardRefreshIntervalField.getText());
    int messageBrowserPageSize = Integer.parseInt(messageBrowserPageSizeField.getText());
    int eventBrowserPageSize = Integer.parseInt(eventBrowserPageSizeField.getText());

    if (interval <= 0) {
        getFrame().alertWarning(this, "Please enter an interval time that is larger than 0.");
    } else if (messageBrowserPageSize <= 0) {
        getFrame().alertWarning(this, "Please enter an message browser page size larger than 0.");
    } else if (eventBrowserPageSize <= 0) {
        getFrame().alertWarning(this, "Please enter an event browser page size larger than 0.");
    } else {
        userPreferences.putInt("intervalTime", interval);
        userPreferences.putInt("messageBrowserPageSize", messageBrowserPageSize);
        userPreferences.putInt("eventBrowserPageSize", eventBrowserPageSize);
        userPreferences.putBoolean("messageBrowserFormat", formatYesRadio.isSelected());
        userPreferences.putBoolean("textSearchWarning", textSearchWarningYesRadio.isSelected());

        if (importChannelLibrariesAskRadio.isSelected()) {
            userPreferences.remove("importChannelCodeTemplateLibraries");
        } else {
            userPreferences.putBoolean("importChannelCodeTemplateLibraries",
                    importChannelLibrariesYesRadio.isSelected());
        }

        if (exportChannelLibrariesAskRadio.isSelected()) {
            userPreferences.remove("exportChannelCodeTemplateLibraries");
        } else {
            userPreferences.putBoolean("exportChannelCodeTemplateLibraries",
                    exportChannelLibrariesYesRadio.isSelected());
        }
    }
    final String workingId = getFrame().startWorking("Saving " + getTabName() + " settings...");

    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        public Void doInBackground() {
            try {
                getFrame().mirthClient.setUserPreference(currentUser.getId(), "checkForNotifications",
                        Boolean.toString(checkForNotificationsYesRadio.isSelected()));
            } catch (ClientException e) {
                getFrame().alertThrowable(getFrame(), e);
            }

            return null;
        }

        @Override
        public void done() {
            getFrame().setSaveEnabled(false);
            getFrame().stopWorking(workingId);
        }
    };

    worker.execute();

    RSTAPreferences rstaPreferences = MirthRSyntaxTextArea.getRSTAPreferences();
    for (int row = 0; row < shortcutKeyTable.getRowCount(); row++) {
        ActionInfo actionInfo = (ActionInfo) shortcutKeyTable.getModel().getValueAt(row, ACTION_INFO_COLUMN);
        KeyStroke keyStroke = (KeyStroke) shortcutKeyTable.getModel().getValueAt(row, KEY_COLUMN);
        rstaPreferences.getKeyStrokeMap().put(actionInfo.getActionMapKey(), keyStroke);
    }
    MirthRSyntaxTextArea.updateKeyStrokePreferences(userPreferences);

    AutoCompleteProperties autoCompleteProperties = rstaPreferences.getAutoCompleteProperties();
    autoCompleteProperties.setActivateAfterLetters(autoCompleteIncludeLettersCheckBox.isSelected());
    autoCompleteProperties.setActivateAfterOthers(autoCompleteCharactersField.getText());
    autoCompleteProperties.setActivationDelay(NumberUtils.toInt(autoCompleteDelayField.getText()));
    MirthRSyntaxTextArea.updateAutoCompletePreferences(userPreferences);

    return true;
}

From source file:org.usfirst.frc.team2084.neuralnetwork.HeadingNeuralNetworkTrainer.java

private void trainNetwork() {
    if (!training) {

        // Set training flag and disable button
        training = true;/*from  ww w.  j a  va2s .  com*/
        trainButton.setEnabled(false);

        final ProgressMonitor progressMonitor = new ProgressMonitor(frame, "Training Network...", "", 0, 100);
        progressMonitor.setMillisToDecideToPopup(100);
        progressMonitor.setMillisToPopup(400);

        @SuppressWarnings("unchecked")
        final ArrayList<XYDataItem> data = new ArrayList<>(outputGraphDataSeries.getItems());

        final int maxProgress = iterations * data.size();

        final SwingWorker<Void, Void> trainingWorker = new SwingWorker<Void, Void>() {

            @Override
            protected Void doInBackground() throws Exception {
                // Reset the neural network to default values
                synchronized (this) {
                    network.reset();
                    network.setEta(eta);
                    network.setMomentum(momentum);
                }

                outer: for (int j = 0; j < iterations; j++) {
                    for (int i = 0; i < data.size(); i++) {
                        if (!isCancelled()) {
                            XYDataItem d = data.get(i);
                            double error = convertAngleToInput(d.getXValue());
                            double output = d.getYValue();
                            synchronized (this) {
                                network.feedForward(error);
                                network.backPropagation(output);
                            }
                            int jl = j;
                            int il = i;
                            int progress = (int) (((float) (data.size() * jl + il + 1) / maxProgress) * 100);
                            setProgress(progress);
                        } else {
                            break outer;
                        }
                    }
                }

                displayNetwork();
                return null;
            }

            @Override
            protected void done() {
                training = false;
                trainButton.setEnabled(true);
                progressMonitor.close();
            }
        };
        trainingWorker.addPropertyChangeListener(new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if (evt.getPropertyName().equals("progress")) {
                    progressMonitor.setProgress((int) evt.getNewValue());
                }
                if (progressMonitor.isCanceled()) {
                    trainingWorker.cancel(true);
                }
            }
        });
        trainingWorker.execute();
    }
}

From source file:com.orthancserver.DicomDecoder.java

public DicomDecoder(final OrthancConnection c, boolean isInstance, String uuid)
        throws IOException, InterruptedException, ExecutionException {
    ImageStack stack = null;//from  w  ww.  j ava  2 s .  c  o 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);
}