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:edu.ku.brc.specify.datamodel.busrules.CollectionBusRules.java

@Override
public void okToDelete(final Object dataObj, final DataProviderSessionIFace session,
        final BusinessRulesOkDeleteIFace deletable) {
    reasonList.clear();/* w  w w.  ja v  a  2 s  .com*/

    if (deletable != null) {
        Collection collection = (Collection) dataObj;

        Integer id = collection.getId();
        if (id != null) {
            Collection currCollection = AppContextMgr.getInstance().getClassObject(Collection.class);
            if (currCollection.getId().equals(collection.getId())) {
                UIRegistry.showLocalizedError("CollectionBusRule.CURR_COL_ERR");

            } else {
                DataProviderSessionIFace pSession = null;
                try {
                    pSession = session != null ? session : DataProviderFactory.getInstance().createSession();

                    pSession.attach(collection);

                    if (collection.getLeftSideRelTypes().size() > 0
                            || collection.getRightSideRelTypes().size() > 0) {

                        if (pSession != null && session == null) {
                            pSession.close();
                        }
                        UIRegistry.showLocalizedError("CollectionBusRule.RELS_ERR");
                        return;
                    }

                    pSession.beginTransaction();

                    Set<AutoNumberingScheme> colANSSet = collection.getNumberingSchemes();
                    for (AutoNumberingScheme ans : new Vector<AutoNumberingScheme>(colANSSet)) {
                        pSession.attach(ans);
                        //System.out.println("Removing: "+ans.getSchemeName()+", "+ans.getFormatName()+" "+ans.getTableNumber()+" disp: "+ans.getDisciplines().size()+" div: "+ans.getDivisions().size());
                    }
                    //System.out.println("----------------------");

                    for (AutoNumberingScheme ans : new Vector<AutoNumberingScheme>(colANSSet)) {
                        //System.out.println("Removing: "+ans.getSchemeName()+", "+ans.getFormatName()+" "+ans.getTableNumber()+" "+ans.getDisciplines().size()+" "+ans.getDivisions().size());

                        pSession.attach(ans);

                        colANSSet.remove(ans);
                        ans.getCollections().remove(collection);

                        if (ans.getCollections().size() == 0) {
                            pSession.delete(ans);
                        }
                    }
                    pSession.saveOrUpdate(collection);
                    pSession.commit();

                    final Integer collId = collection.getId();
                    final SpecifyDeleteHelper delHelper = new SpecifyDeleteHelper();

                    SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() {
                        /* (non-Javadoc)
                         * @see javax.swing.SwingWorker#doInBackground()
                         */
                        @Override
                        protected Integer doInBackground() throws Exception {
                            try {
                                delHelper.delRecordFromTable(Collection.class, collId, true);
                                delHelper.done(false);

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

                            return null;
                        }

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

                            SwingUtilities.invokeLater(new Runnable() {
                                @Override
                                public void run() {
                                    // This is called instead of calling 'okToDelete' because we had the SpecifyDeleteHelper
                                    // delete the actual dataObj and now we tell the form to remove the dataObj from
                                    // the form's list and them update the controller appropriately
                                    if (formViewObj != null) {
                                        formViewObj.updateAfterRemove(true); // true removes item from list and/or set
                                    }

                                    UIRegistry.showLocalizedMsg("Specify.ABT_EXIT");
                                    CommandDispatcher.dispatch(
                                            new CommandAction(BaseTask.APP_CMD_TYPE, BaseTask.APP_REQ_EXIT));
                                }
                            });
                        }
                    };

                    String title = String.format("%s %s %s", getResourceString("DELETING"),
                            DBTableIdMgr.getInstance().getTitleForId(Collection.getClassTableId()),
                            collection.getCollectionName());

                    JDialog dlg = delHelper.initProgress(worker, title);

                    worker.execute();

                    UIHelper.centerAndShow(dlg);

                } catch (Exception ex) {
                    ex.printStackTrace();
                    edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DisciplineBusRules.class, ex);
                }
            }
        } else {
            super.okToDelete(dataObj, session, deletable);
        }
    } else {
        super.okToDelete(dataObj, session, deletable);
    }
}

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

private void useTrialKeyButtonActionPerformed(ActionEvent evt) {

    /**/*  ww  w.  jav a2 s  . c  om*/
     * First validate license and get a temporary license object to
     * check for validation status later.
     */
    License temporaryLicenseObject = LicenseValidator.validate(trialLicKey, publicKey, internalString,
            nameforValidation, companyforValidation, hardwareIDMethod);

    /**
     * If given license key is valid, then save it on disk, and update
     * GUI fields.
     */
    if (temporaryLicenseObject.getValidationStatus() == ValidationStatus.LICENSE_VALID) {
        licenseObject = temporaryLicenseObject;

        try {
            /**
             * We use Apache commons-io (FileUtils class) to easily save
             * string to file.
             */
            FileUtils.writeStringToFile(new File(licenseKeyFileOnDisk), trialLicKey);

            /**
             * Since license key is changed delete license text file if
             * exists on disk left from previous license key.
             */
            FileUtils.deleteQuietly(new File(licenseTextFileOnDisk));
        } catch (IOException ex) {
            Logger.getLogger(LicenseKeyGUI.class.getName()).log(Level.SEVERE, null, ex);
        }

        updateGUIFieldsWithLicenseObject();

        /**
         * 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);

    } else {
        /**
         * If given license is not valid, display an error message.
         */
        JOptionPane.showMessageDialog(null, "License error: " + temporaryLicenseObject.getValidationStatus(),
                "License Error", JOptionPane.ERROR_MESSAGE);
    }

}

From source file:co.edu.unal.pos.gui.PosHadoopJFrame.java

private void saveConfigurationJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_configurationJButtonActionPerformed
    SwingWorker<Void, Void> swingWorker = new SwingWorker<Void, Void>() {

        @Override//from   w w  w  .ja  va 2 s  .  c  om
        protected Void doInBackground() throws Exception {
            disableGUI();
            properties.clear();
            for (int i = 0; i < configurationTableDataModel.getRowCount(); i++) {
                properties.put(configurationTableDataModel.getValueAt(i, 0).toString(),
                        configurationTableDataModel.getValueAt(i, 1).toString());
            }
            PropertiesProvider.getInstance().saveProperties(properties);
            enableGUI();
            return null;
        }

    };
    swingWorker.execute();
}

From source file:co.edu.unal.pos.gui.PosHadoopJFrame.java

public void updatePropertiesTableDataModel() {
    SwingWorker<Void, Void> swingWorker = new SwingWorker<Void, Void>() {

        @Override/*from  w w  w  .ja va 2 s .c o  m*/
        protected Void doInBackground() throws Exception {
            disableGUI();
            etlJProgressBar.setStringPainted(true);
            etlJProgressBar.setIndeterminate(true);
            etlJProgressBar.setString("Loading application...");
            Map<String, String> properties = PropertiesProvider.getInstance().getProperties();
            String[][] propertiesTableDataModel = new String[properties.size()][2];
            int i = 0;
            for (Map.Entry<String, String> property : properties.entrySet()) {
                propertiesTableDataModel[i][0] = property.getKey();
                propertiesTableDataModel[i][1] = property.getValue();
                i++;
            }
            setConfigurationTableDataModel(propertiesTableDataModel);
            etlJProgressBar.setString("");
            etlJProgressBar.setIndeterminate(false);
            enableGUI();
            return null;
        }

    };
    swingWorker.execute();
}

From source file:edu.ku.brc.specify.dbsupport.cleanuptools.GeoCleanupFuzzySearch.java

/**
* @param earthId/*from  w  w w.  java  2 s .  co  m*/
* @param cl
*/
public void startIndexingProcessAsync(final int earthId, final ProgressFrame frame, final ChangeListener cl) {
    this.frame = frame;

    centerAndShow(frame);

    SwingWorker<Boolean, Boolean> worker = new SwingWorker<Boolean, Boolean>() {
        boolean isOK = true;

        @Override
        protected Boolean doInBackground() throws Exception {
            setProgressDesc("Build Geography Names cross-reference..."); // I18N
            stCntXRef = new StateCountryContXRef(readConn);
            isOK = stCntXRef.build();
            if (isOK) {
                setProgressDesc("Creating searchable index..."); // I18N
                isOK = buildLuceneIndex(earthId);
            }
            return isOK;
        }

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

            // NOTE: need to check here that everything built OK
            cl.stateChanged(new ChangeEvent((Boolean) isOK));
        }
    };
    worker.execute();
}

From source file:es.emergya.ui.gis.popups.ConsultaHistoricos.java

private void addCapa(final Layer layer) {
    SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {
        @Override/* www  .ja v  a 2 s. c o  m*/
        protected Object doInBackground() throws Exception {
            layer.visible = true;
            if (!Main.pref.putColor("layer " + layer.name, Color.decode(LogicConstants.getNextColor()))) {
                log.error("Error al asignar el color");
            }
            return null;
        }

        @Override
        protected void done() {
            super.done();
            mapView.addLayer(layer, false);
            capas.add(layer);
            limpiar.setEnabled(true);

            HistoryMapViewer.enableSaveGpx(true);
        }
    };
    sw.execute();
}

From source file:org.esa.snap.rcp.statistics.ScatterPlotPanel.java

private void compute(final Mask selectedMask) {

    final RasterDataNode raster = getRaster();

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

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

        @Override
        protected ComputedData[] doInBackground() throws Exception {
            SystemUtils.LOG.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.getRasterWidth(), raster.getRasterHeight());

            final GeoCoding geoCoding = raster.getGeoCoding();
            final AffineTransform imageToModelTransform;
            imageToModelTransform = Product.findImageToModelTransform(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, (float) geoPos.getLat(), (float) 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) {
                SystemUtils.LOG.log(Level.WARNING, "Failed to compute correlative plot.", e);
                Dialogs.showMessage(CHART_TITLE,
                        "Failed to compute correlative plot.\n" + "Calculation canceled.",
                        JOptionPane.ERROR_MESSAGE, null);
            } catch (ExecutionException e) {
                SystemUtils.LOG.log(Level.WARNING, "Failed to compute correlative plot.", e);
                Dialogs.showMessage(CHART_TITLE, "Failed to compute correlative plot.\n"
                        + "An error occurred:\n" + e.getCause().getMessage(), JOptionPane.ERROR_MESSAGE, null);
            }
        }
    };
    swingWorker.execute();
}

From source file:es.emergya.ui.gis.popups.ConsultaHistoricos.java

private synchronized void cleanLayers() {
    SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {
        @Override/*  ww w .ja v a  2s .c  o m*/
        protected Object doInBackground() throws Exception {
            return null;
        }

        @Override
        protected void done() {
            for (Layer layer : capas) {
                mapView.removeLayer(layer);
            }
            capas.clear();
            mapView.repaint();
            LogicConstants.resetColor();
        }
    };
    sw.execute();
}

From source file:es.emergya.ui.plugins.admin.AdminLayers.java

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

        private static final long serialVersionUID = 912391796510206341L;

        @Override/*from w w  w .j a v a2  s  .com*/
        public void actionPerformed(ActionEvent e) {
            log.debug("subeCapaAction(" + capa + ")");
            SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {

                @Override
                protected Object doInBackground() throws Exception {
                    CapaInformacionAdmin.sube(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 setCuenta(final int showed, final int total) {

    SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {

        @Override//  w  w  w.java  2  s  .c  om
        protected Object doInBackground() throws Exception {
            setSize(total);
            return null;
        }

        @Override
        protected void done() {
            cuenta.setText("(" + showed + "/" + total + ")");
            filters.updateUI();
        }
    };
    sw.execute();
}