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:es.emergya.ui.plugins.admin.AdminLayers.java

protected Action bajaCapaAction(final CapaInformacion capa) {
    Action a = new AbstractAction("", LogicConstants.getIcon("button_down")) {

        private static final long serialVersionUID = -4001983030571380494L;

        @Override//from   w w w .j  a  va2s .  c  om
        public void actionPerformed(ActionEvent e) {
            log.debug("bajaCapaAction(" + capa + ")");
            SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {

                @Override
                protected Object doInBackground() throws Exception {
                    CapaInformacionAdmin.baja(capa);
                    return null;
                }

                @Override
                protected void done() {
                    super.done();
                    AdminLayers.this.refresh(null);
                }
            };
            sw.execute();
        }
    };

    return a;
}

From source file:es.emergya.ui.plugins.AdminPanel.java

public void changeRow(final int fila, final int destino) {
    SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {

        @Override//from   www . j ava 2s .c  om
        protected void done() {
            ((MyTableModel) table.getModel()).changeRow(fila, destino);
        }

        @Override
        protected Object doInBackground() throws Exception {
            return null;
        }
    };
    sw.execute();
}

From source file:com.josescalia.tumblr.form.TumblrImageViewer.java

private void btnDownloadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDownloadActionPerformed
    frame = (MainFrame) this.getTopLevelAncestor();
    form = this;//from w  ww .j av  a2s .  c om
    /*since the application using cache, all we need is only copying target file to destination folder*/

    //busy cursor and progress bar panel and frame
    form.setCursor(new Cursor(Cursor.WAIT_CURSOR));
    frame.setCursor(new Cursor(Cursor.WAIT_CURSOR));
    frame.startProgressBar("Downloading");
    new SwingWorker<String, String>() {
        @Override
        protected String doInBackground() throws Exception {
            int successCount = 0;
            int failedCount = 0;
            for (DownloadableImage image : imgList) {
                String fileName = image.getUrl().substring(image.getUrl().lastIndexOf("/") + 1);
                String downloadUrl = image.getUrl();
                File targetFile = new File(BinaryCacheUtil.getBinaryImagePath(".cache", fileName, downloadUrl));
                try {
                    FileSystemUtils.copyRecursively(targetFile, new File(downloadPath + "//" + fileName));
                    successCount++;
                } catch (IOException e) {
                    logger.error("Copy Failed Exception : " + e.getMessage());
                    failedCount++;
                }
            }
            return "Download file finished : \n" + successCount + " file(s) downloaded successfully \n"
                    + failedCount + "failed to download";
        }

        @Override
        protected void done() {
            try {
                UIAlert.showInformation(null, get());
            } catch (InterruptedException e) {
                logger.error(e);
            } catch (ExecutionException e) {
                logger.error(e);
            }
            form.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            frame.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            frame.stopProgressBar("");
        }
    }.execute();

}

From source file:edu.ku.brc.specify.tasks.subpane.lm.LifeMapperPane.java

/**
 * //from w  w  w.  ja  v  a 2s .co  m
 */
@SuppressWarnings("unchecked")
public void doSearchOccur(final String occurrenceId) {
    updateMyDataUIState(false);

    points.clear();

    final SimpleGlassPane glassPane = writeSimpleGlassPaneMsg(getLocalizedMessage("LifeMapperTask.PROCESSING"),
            GLASS_FONT_SIZE);
    glassPane.setTextYPos((int) ((double) getSize().height * 0.25));

    // check the website for the info about the latest version
    final HttpClient httpClient = new HttpClient();
    httpClient.getParams().setParameter("http.useragent", getClass().getName()); //$NON-NLS-1$
    httpClient.getParams().setParameter("http.socket.timeout", 15000);

    if (list.getSelectedIndex() < 0) {
        return;
    }

    UsageTracker.incrUsageCount("LM.OccurSearch");

    final String lmURL = String.format(
            "http://www.lifemapper.org/services/sdm/occurrences/%s/json?format=specify&fillPoints=true",
            occurrenceId);
    //System.out.println(lmURL);

    SwingWorker<String, String> worker = new SwingWorker<String, String>() {
        @Override
        protected String doInBackground() throws Exception {
            GetMethod getMethod = new GetMethod(lmURL);
            try {
                httpClient.executeMethod(getMethod);

                // get the server response
                //String responseString = getMethod.getResponseBodyAsString();
                byte[] bytes = getMethod.getResponseBody();
                if (bytes != null && bytes.length > 0) {
                    return new String(bytes, "UTF-8");
                }
                //if (StringUtils.isNotEmpty(responseString))
                //{
                //    System.err.println(responseString);
                //}
                return null;
            } catch (java.net.UnknownHostException uex) {
                //log.error(uex.getMessage());
            } catch (java.net.SocketTimeoutException ex) {
                UsageTracker.incrUsageCount("LM.OccurSearchErr");
            } catch (Exception e) {
                e.printStackTrace();
                UsageTracker.incrUsageCount("LM.OccurSearchErr");
            }

            return null;
        }

        @Override
        protected void done() {
            super.done();

            boolean isError = true;
            boolean parseError = false;

            try {
                String responseString = get();

                if (StringUtils.isNotEmpty(responseString)
                        && StringUtils.contains(responseString.toLowerCase(), "{")) {
                    // Need to change this to using regex to strip away unwanted chars
                    StringBuilder sb = new StringBuilder();
                    String[] lines = StringUtils.split(responseString, '\n');
                    for (String str : lines) {
                        if (str.indexOf("resname") == -1) {
                            sb.append(str);
                        }
                    }
                    String cleaned = sb.toString();

                    parseError = false;
                    try {
                        JSONTokener tok = new JSONTokener(cleaned);
                        if (tok != null) {
                            while (tok.more()) {
                                JSONObject obj = (JSONObject) tok.nextValue();
                                if (obj != null) {
                                    JSONArray pointArray = (JSONArray) obj.get("feature");
                                    if (pointArray != null) {
                                        Iterator<Object> iter = (Iterator<Object>) pointArray.iterator();
                                        while (iter.hasNext()) {
                                            JSONObject pObj = (JSONObject) iter.next();
                                            if (pObj != null) {
                                                String lat = null;//(String)pObj.get("lat");
                                                String lon = null;//(String)pObj.get("lon");
                                                String geomwkt = (String) pObj.get("geomwkt");
                                                if (geomwkt != null) {
                                                    //quel cheapo...
                                                    geomwkt = geomwkt.replace("POINT", "");
                                                    geomwkt = geomwkt.replace("(", "");
                                                    geomwkt = geomwkt.replace(")", "");
                                                    geomwkt = geomwkt.trim();
                                                    String[] geocs = geomwkt.split(" ");
                                                    if (geocs.length == 2) {
                                                        lon = geocs[0];
                                                        lat = geocs[1];
                                                    }
                                                }
                                                //System.out.println(lat+"  "+lon);
                                                if (lat != null && lon != null) {
                                                    LatLonPlacemark plcMark = new LatLonPlacemark(markerImg,
                                                            Double.parseDouble(lat.trim()),
                                                            Double.parseDouble(lon.trim()));
                                                    points.add(plcMark);
                                                }
                                            }
                                        }
                                        isError = false;
                                    }
                                }
                            }
                        }
                    } catch (net.sf.json.JSONException ex) {
                        System.err.println(ex.getLocalizedMessage());
                        parseError = true;
                    }

                    boolean hasPnts = points.size() > 0;
                    updateMyDataUIState(hasPnts && StringUtils.isNotEmpty(myDataTF.getText()));
                    if (hasPnts) {
                        imgDisplay.setImage((Image) null);
                        wwPanel.placeMarkers(points, false, true, 0, null, false);

                        imgRequestCnt = 0;

                        imgURL = makeURL(occurSet);

                        getImageFromWeb(imgURL, pointsMapImageListener);

                    } else {
                        isError = false;
                    }

                } else {
                    UsageTracker.incrUsageCount("LM.OccurSearchErr");
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }

            if (isError || parseError) {
                showErrorMsg(glassPane, "LifeMapperTask.PROC_ERR");
            } else {
                clearSimpleGlassPaneMsg();
            }
        }
    };
    worker.execute();
}

From source file:org.esa.beam.visat.toolviews.stat.ScatterPlotPanel.java

private void compute(final Mask selectedMask) {

    final RasterDataNode raster = getRaster();

    final AttributeDescriptor dataField = scatterPlotModel.dataField;
    if (raster == null || dataField == null) {
        return;/*from w ww. java  2 s  .c o  m*/
    }

    SwingWorker<ComputedData[], Object> swingWorker = new SwingWorker<ComputedData[], Object>() {

        @Override
        protected ComputedData[] doInBackground() throws Exception {
            BeamLogManager.getSystemLogger().finest("start computing scatter plot data");

            final List<ComputedData> computedDataList = new ArrayList<>();

            final FeatureCollection<SimpleFeatureType, SimpleFeature> collection = scatterPlotModel.pointDataSource
                    .getFeatureCollection();
            final SimpleFeature[] features = collection.toArray(new SimpleFeature[collection.size()]);

            final int boxSize = scatterPlotModel.boxSize;

            final Rectangle sceneRect = new Rectangle(raster.getSceneRasterWidth(),
                    raster.getSceneRasterHeight());

            final GeoCoding geoCoding = raster.getGeoCoding();
            final AffineTransform imageToModelTransform;
            imageToModelTransform = ImageManager.getImageToModelTransform(geoCoding);
            for (SimpleFeature feature : features) {
                final Point point = (Point) feature.getDefaultGeometryProperty().getValue();
                Point2D modelPos = new Point2D.Float((float) point.getX(), (float) point.getY());
                final Point2D imagePos = imageToModelTransform.inverseTransform(modelPos, null);

                if (!sceneRect.contains(imagePos)) {
                    continue;
                }
                final float imagePosX = (float) imagePos.getX();
                final float imagePosY = (float) imagePos.getY();
                final Rectangle imageRect = sceneRect.intersection(new Rectangle(
                        ((int) imagePosX) - boxSize / 2, ((int) imagePosY) - boxSize / 2, boxSize, boxSize));
                if (imageRect.isEmpty()) {
                    continue;
                }
                final double[] rasterValues = new double[imageRect.width * imageRect.height];
                raster.readPixels(imageRect.x, imageRect.y, imageRect.width, imageRect.height, rasterValues);

                final int[] maskBuffer = new int[imageRect.width * imageRect.height];
                Arrays.fill(maskBuffer, 1);
                if (selectedMask != null) {
                    selectedMask.readPixels(imageRect.x, imageRect.y, imageRect.width, imageRect.height,
                            maskBuffer);
                }

                final int centerIndex = imageRect.width * (imageRect.height / 2) + (imageRect.width / 2);
                if (maskBuffer[centerIndex] == 0) {
                    continue;
                }

                double sum = 0;
                double sumSqr = 0;
                int n = 0;
                boolean valid = false;

                for (int y = 0; y < imageRect.height; y++) {
                    for (int x = 0; x < imageRect.width; x++) {
                        final int index = y * imageRect.height + x;
                        if (raster.isPixelValid(x + imageRect.x, y + imageRect.y) && maskBuffer[index] != 0) {
                            final double rasterValue = rasterValues[index];
                            sum += rasterValue;
                            sumSqr += rasterValue * rasterValue;
                            n++;
                            valid = true;
                        }
                    }
                }

                if (!valid) {
                    continue;
                }

                double rasterMean = sum / n;
                double rasterSigma = n > 1 ? Math.sqrt((sumSqr - (sum * sum) / n) / (n - 1)) : 0.0;

                String localName = dataField.getLocalName();
                Number attribute = (Number) feature.getAttribute(localName);

                final Collection<org.opengis.feature.Property> featureProperties = feature.getProperties();

                final float correlativeData = attribute.floatValue();
                final GeoPos geoPos = new GeoPos();
                if (geoCoding.canGetGeoPos()) {
                    final PixelPos pixelPos = new PixelPos(imagePosX, imagePosY);
                    geoCoding.getGeoPos(pixelPos, geoPos);
                } else {
                    geoPos.setInvalid();
                }
                computedDataList.add(new ComputedData(imagePosX, imagePosY, geoPos.getLat(), geoPos.getLon(),
                        (float) rasterMean, (float) rasterSigma, correlativeData, featureProperties));
            }

            return computedDataList.toArray(new ComputedData[computedDataList.size()]);
        }

        @Override
        public void done() {
            try {
                final ValueAxis xAxis = getPlot().getDomainAxis();
                final ValueAxis yAxis = getPlot().getRangeAxis();

                xAxis.setAutoRange(false);
                yAxis.setAutoRange(false);

                scatterpointsDataset.removeAllSeries();
                acceptableDeviationDataset.removeAllSeries();
                regressionDataset.removeAllSeries();
                getPlot().removeAnnotation(r2Annotation);
                computedDatas = null;

                final ComputedData[] data = get();
                if (data.length == 0) {
                    return;
                }

                computedDatas = data;

                final XYIntervalSeries scatterValues = new XYIntervalSeries(getCorrelativeDataName());
                for (ComputedData computedData : computedDatas) {
                    final float rasterMean = computedData.rasterMean;
                    final float rasterSigma = computedData.rasterSigma;
                    final float correlativeData = computedData.correlativeData;
                    scatterValues.add(correlativeData, correlativeData, correlativeData, rasterMean,
                            rasterMean - rasterSigma, rasterMean + rasterSigma);
                }

                computingData = true;
                scatterpointsDataset.addSeries(scatterValues);

                xAxis.setAutoRange(true);
                yAxis.setAutoRange(true);

                xAxis.setAutoRange(false);
                yAxis.setAutoRange(false);

                xAutoRangeAxisRange = new Range(xAxis.getLowerBound(), xAxis.getUpperBound());
                yAutoRangeAxisRange = new Range(yAxis.getLowerBound(), yAxis.getUpperBound());

                if (xAxisRangeControl.isAutoMinMax()) {
                    xAxisRangeControl.adjustComponents(xAxis, 3);
                } else {
                    xAxisRangeControl.adjustAxis(xAxis, 3);
                }
                if (yAxisRangeControl.isAutoMinMax()) {
                    yAxisRangeControl.adjustComponents(yAxis, 3);
                } else {
                    yAxisRangeControl.adjustAxis(yAxis, 3);
                }

                computeRegressionAndAcceptableDeviationData();
                computingData = false;
            } catch (InterruptedException | CancellationException e) {
                BeamLogManager.getSystemLogger().log(Level.WARNING, "Failed to compute correlative plot.", e);
                JOptionPane.showMessageDialog(getParentDialogContentPane(),
                        "Failed to compute correlative plot.\n" + "Calculation canceled.",
                        /*I18N*/
                        CHART_TITLE, /*I18N*/
                        JOptionPane.ERROR_MESSAGE);
            } catch (ExecutionException e) {
                BeamLogManager.getSystemLogger().log(Level.WARNING, "Failed to compute correlative plot.", e);
                JOptionPane.showMessageDialog(getParentDialogContentPane(),
                        "Failed to compute correlative plot.\n" + "An error occurred:\n"
                                + e.getCause().getMessage(),
                        CHART_TITLE, /*I18N*/
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    };
    swingWorker.execute();
}

From source file:es.emergya.ui.plugins.AdminPanel.java

public void setFilter(final Integer i, final String[] items) {
    SwingWorker<JComboBox, Object> sw = new SwingWorker<JComboBox, Object>() {
        @Override/*from  w  w  w .  jav  a 2  s .c o m*/
        protected JComboBox doInBackground() throws Exception {
            JComboBox cb = setComboBoxEditor(i - 1, items);
            return cb;
        }

        @Override
        protected void done() {
            if (filters.getCellEditor() != null)
                filters.getCellEditor().cancelCellEditing();
            filters.repaint();
        }
    };

    sw.execute();
}

From source file:com.pianobakery.complsa.LicenseKeyGUI.java

private void activatejButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_activatejButtonActionPerformed
    /**//  ww w.j ava  2  s.co  m
     * We use a SwingWorker here because it will connect to license server
     * for activation, and it may take 2-3 seconds.
     */
    SwingWorker<License, Void> worker = new SwingWorker<License, Void>() {
        @Override
        protected void done() {
            try {
                /**
                 * Again we get license object to a temporary object to
                 * check for ActivationStatus.
                 */
                License temporaryLicenseObject = (License) get();

                /**
                 * If it is successfully activated save on disk and update
                 * GUI fields.
                 */
                if (temporaryLicenseObject.getActivationStatus() == ActivationStatus.ACTIVATION_COMPLETED) {
                    licenseObject = temporaryLicenseObject;

                    try {
                        /**
                         * We use Apache commons-io (FileUtils class) to
                         * easily save string to file.
                         *
                         * licenseObject.getLicenseString() method returns
                         * activated license string.
                         */
                        FileUtils.writeStringToFile(new File(licenseTextFileOnDisk),
                                licenseObject.getLicenseString());
                    } catch (IOException ex) {
                        Logger.getLogger(LicenseKeyGUI.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    updateGUIFieldsWithLicenseObject();
                } else {
                    /**
                     * If activation cannot be completed, display an error
                     * message.
                     */
                    JOptionPane.showMessageDialog(null,
                            "License activation error: " + temporaryLicenseObject.getActivationStatus(),
                            "Activation Error", JOptionPane.ERROR_MESSAGE);
                }
            } catch (InterruptedException ex) {
                Logger.getLogger(LicenseKeyGUI.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ExecutionException ex) {
                Logger.getLogger(LicenseKeyGUI.class.getName()).log(Level.SEVERE, null, ex);
            }

            progressjLabel.setText("");

            /**
             * Activation progress is complete, enable buttons again.
             */
            activatejButton.setEnabled(true);
            changeProductKeyjButton.setEnabled(true);
            JOptionPane.showMessageDialog(null, "Please restart to enable the license", "Restart...",
                    JOptionPane.INFORMATION_MESSAGE);
        }

        @Override
        protected License doInBackground() {
            /**
             * Since example licenses are on Online.License4J the method
             * below will activate on Online.License4J when autoActivate
             * method is called without a license server address.
             */
            return LicenseValidator.autoActivate(licenseObject);

            /**
             * If you want to test your own "Auto License Generation and
             * Activation Server" you should give its address as argument
             * like below.
             */
            //return LicenseValidator.autoActivate(licenseObject, "http://YourServer.com/algas/autoactivate");
        }
    };
    worker.execute();

    progressjLabel.setText("Activating ...");

    /**
     * It is good to disable "activate" and "change product key" buttons
     * while activation is in progress.
     */
    activatejButton.setEnabled(false);
    changeProductKeyjButton.setEnabled(false);
}

From source file:com.marginallyclever.makelangelo.MainGUI.java

public boolean LoadImage(String filename) {
    // where to save temp output file?
    final String sourceFile = filename;
    final String destinationFile = GetTempDestinationFile();

    LoadImageConverters();/*from w  ww .  java  2  s.c  o  m*/
    if (ChooseImageConversionOptions(false) == false)
        return false;

    final ProgressMonitor pm = new ProgressMonitor(null, translator.get("Converting"), "", 0, 100);
    pm.setProgress(0);
    pm.setMillisToPopup(0);

    final SwingWorker<Void, Void> s = new SwingWorker<Void, Void>() {
        @Override
        public Void doInBackground() {
            // read in image
            BufferedImage img;
            try {
                Log("<font color='green'>" + translator.get("Converting") + " " + destinationFile
                        + "</font>\n");
                // convert with style
                img = ImageIO.read(new File(sourceFile));
                int style = GetDrawStyle();
                Filter f = image_converters.get(style);
                TabToLog();
                f.SetParent(this);
                f.SetProgressMonitor(pm);
                f.SetDestinationFile(destinationFile);
                f.Convert(img);
                TabToDraw();
                previewPane.ZoomToFitPaper();
            } catch (IOException e) {
                Log("<font color='red'>" + translator.get("Failed") + e.getLocalizedMessage() + "</font>\n");
                recentFiles.remove(sourceFile);
                updateMenuBar();
            }

            pm.setProgress(100);
            return null;
        }

        @Override
        public void done() {
            pm.close();
            Log("<font color='green'>" + translator.get("Finished") + "</font>\n");
            PlayConversionFinishedSound();
            LoadGCode(destinationFile);
        }
    };

    s.addPropertyChangeListener(new PropertyChangeListener() {
        // Invoked when task's progress property changes.
        public void propertyChange(PropertyChangeEvent evt) {
            if ("progress" == evt.getPropertyName()) {
                int progress = (Integer) evt.getNewValue();
                pm.setProgress(progress);
                String message = String.format("%d%%.\n", progress);
                pm.setNote(message);
                if (s.isDone()) {
                    Log("<font color='green'>" + translator.get("Finished") + "</font>\n");
                } else if (s.isCancelled() || pm.isCanceled()) {
                    if (pm.isCanceled()) {
                        s.cancel(true);
                    }
                    Log("<font color='green'>" + translator.get("Cancelled") + "</font>\n");
                }
            }
        }
    });

    s.execute();

    return true;
}

From source file:edu.ku.brc.specify.config.init.SpecifyDBSetupWizard.java

/**
 * /*w w w .ja  v a  2  s .co m*/
 */
public void configureDatabase() {
    if (wizardType == WizardType.Institution) {
        setupLoginPrefs();
    }

    if (SpecifyDBSetupWizard.this.listener != null) {
        SpecifyDBSetupWizard.this.listener.hide();
    }

    SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() {
        protected boolean isOK = false;

        /* (non-Javadoc)
         * @see javax.swing.SwingWorker#doInBackground()
         */
        @Override
        protected Integer doInBackground() throws Exception {
            try {
                String dbName = props.getProperty("dbName");
                String hostName = props.getProperty("hostName");
                DatabaseDriverInfo driverInfo = (DatabaseDriverInfo) props.get("driverObj");

                String connStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Create, hostName,
                        dbName);
                if (connStr == null) {
                    connStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, hostName,
                            dbName);
                }

                String saUserName = props.getProperty("saUserName"); // Master Username
                String saPassword = props.getProperty("saPassword"); // Master Password

                BuildSampleDatabase bsd = new BuildSampleDatabase();

                progressFrame = bsd.createProgressFrame(getResourceString("CREATE_DIV"));
                progressFrame.adjustProgressFrame();
                progressFrame.setProcessPercent(true);
                progressFrame.setOverall(0, 12);
                UIRegistry.pushWindow(progressFrame);

                UIHelper.centerAndShow(progressFrame);

                if (!UIHelper.tryLogin(driverInfo.getDriverClassName(), driverInfo.getDialectClassName(),
                        dbName, connStr, saUserName, saPassword)) {
                    isOK = false;
                    return null;
                }

                Session session = HibernateUtil.getCurrentSession();
                bsd.setSession(session);

                AppContextMgr ac = AppContextMgr.getInstance();
                Institution institution = ac.getClassObject(Institution.class);
                SpecifyUser user = ac.getClassObject(SpecifyUser.class);
                DisciplineType disciplineType = (DisciplineType) props.get("disciplineType");
                DataType dataType = AppContextMgr.getInstance().getClassObject(DataType.class);

                session.lock(institution, LockMode.NONE);
                session.lock(dataType, LockMode.NONE);

                bsd.setDataType(dataType);

                Division division = bsd.createEmptyDivision(institution, disciplineType, user, props, true,
                        true, true);
                if (division != null) {
                    isOK = division != null;

                    progressFrame.incOverall();

                    if (isOK) {
                        SpecifySchemaUpdateService
                                .addIPadExporterTables(DBConnection.getInstance().getConnection());
                        FixDBAfterLogin.fixUserPermissions(true);
                        saveFormatters();
                    }

                    progressFrame.setVisible(false);
                    progressFrame.dispose();
                } else {
                    isOK = false;
                }

            } catch (Exception ex) {
                //edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SpecifyDBSetupWizard.class, ex);
                ex.printStackTrace();
            }
            return null;
        }

        /* (non-Javadoc)
         * @see javax.swing.SwingWorker#done()
         */
        @Override
        protected void done() {
            // Create Version Record and copy if there is a connection
            if (DBConnection.getInstance().getConnection() != null) {
                String resAppVersion = UIRegistry.getAppVersion();
                String dbVersion = SchemaUpdateService.getInstance().getDBSchemaVersionFromXML();
                SpVersion.createInitialRecord(DBConnection.getInstance().getConnection(), resAppVersion,
                        dbVersion);

                if (UIRegistry.isMobile()) {
                    DBConnection.setCopiedToMachineDisk(true);
                }
            }

            JOptionPane.showMessageDialog(UIRegistry.getTopWindow(),
                    getLocalizedMessage("BLD_DONE", getResourceString(isOK ? "BLD_OK" : "BLD_NOTOK")),
                    getResourceString("COMPLETE"), JOptionPane.INFORMATION_MESSAGE);

            if (listener != null) {
                listener.hide();
                listener.finished();
            }
        }
    };
    worker.execute();
}

From source file:edu.ku.brc.specify.tools.StrLocalizerApp.java

/**
 * //  w w w.  j av a2 s  . co  m
 */
private void translateNewItems() {

    //writeGlassPaneMsg(getResourceString("StrLocalizerApp.TranslatingNew"), 24);
    final String STATUSBAR_NAME = "STATUS";
    final JStatusBar statusBar = UIRegistry.getStatusBar();
    statusBar.setProgressRange(STATUSBAR_NAME, 0, 100);

    startTransMenuItem.setEnabled(false);
    stopTransMenuItem.setEnabled(true);

    final double total = newKeyList.size();

    SwingWorker<Integer, Integer> translator = new SwingWorker<Integer, Integer>() {
        @Override
        protected Integer doInBackground() throws Exception {
            int count = 0;
            for (String key : newKeyList) {
                StrLocaleEntry entry = srcFile.getItemHash().get(key);
                //if (StringUtils.contains(entry.getSrcStr(), "%") || StringUtils.contains(entry.getSrcStr(), "\n"))
                {
                    String transText = translate(entry.getSrcStr());
                    if (transText != null) {
                        entry.setDstStr(transText);
                        //writeGlassPaneMsg(String.format("%d / %d", count, newKeyList.size()), 18);
                        //System.out.println(String.format("%s - %d / %d", key, count, newKeyList.size()));
                    }
                }

                try {
                    Thread.sleep(100 + (int) (Math.random() * 100.0));
                } catch (InterruptedException ex) {
                }

                setProgress((int) (((double) count / total) * 100.0));
                System.out.println(entry.getSrcStr() + "  " + count);
                //glassPane.setProgress((int)( (100.0 * count) / total));
                count++;

                if (!contTrans.get()) {
                    return null;
                }
            }
            return null;
        }

        /* (non-Javadoc)
         * @see javax.swing.SwingWorker#done()
         */
        @Override
        protected void done() {
            //glassPane.setProgress(100);
            //clearGlassPaneMsg();

            //statusBar.setIndeterminate(STATUSBAR_NAME, false);
            statusBar.setText("");
            statusBar.setProgressDone(STATUSBAR_NAME);

            UIRegistry.showLocalizedMsg("Done Localizing");

            startTransMenuItem.setEnabled(true);
            stopTransMenuItem.setEnabled(false);

        }
    };

    statusBar.setIndeterminate(STATUSBAR_NAME, true);

    translator.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            //System.out.println(evt.getPropertyName());

            if ("progress".equals(evt.getPropertyName())) {
                statusBar.setText(String.format("%d / 100 ", (Integer) evt.getNewValue()) + "%");
            }
        }
    });
    translator.execute();
}