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:com.dfki.av.sudplan.vis.VisualizationPanel.java

/**
 * Adds a KML file to the world wind model.
 *
 * @param file the {@link File}//from w ww.j  a  v a 2s .c  om
 * @throws IllegalArgumentException if file == null
 * @throws Exception
 */
public void addKMLLayer(File file) throws Exception {
    if (file == null) {
        String msg = "file == null";
        log.error(msg);
        throw new IllegalArgumentException(msg);
    }

    final File kmlFile = file;
    SwingWorker workerThread = new SwingWorker() {

        @Override
        protected Object doInBackground() throws Exception {
            KMLRoot kmlRoot = KMLRoot.createAndParse(kmlFile);
            KMLAbstractFeature rootFeature = kmlRoot.getFeature();
            String layerName = "KML Layer";
            if (rootFeature != null && !WWUtil.isEmpty(rootFeature.getName())) {
                layerName = rootFeature.getName();
            } else if (kmlFile instanceof File) {
                layerName = kmlFile.getName();
            }
            kmlRoot.setField(AVKey.DISPLAY_NAME, layerName);

            KMLController kmlController = new KMLController(kmlRoot);
            // Adds a new layer containing the KMLRoot to the end of the WorldWindow's layer list. This
            // retrieves the layer name from the KMLRoot's DISPLAY_NAME field.
            RenderableLayer layer = new RenderableLayer();
            layer.setName((String) kmlRoot.getField(AVKey.DISPLAY_NAME));
            layer.addRenderable(kmlController);
            ApplicationTemplate.insertBeforePlacenames(wwd, layer);
            return null;
        }
    };
    workerThread.execute();
}

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

private JButton getConsultar() {
    final JButton jButton = new JButton(LogicConstants.getIcon("historico_button_realizarconsulta"));
    jButton.setText("Consultar");
    jButton.setEnabled(false);/*from  w w w . j  av  a2  s  . com*/
    jButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            cargando.setIcon(LogicConstants.getIcon("anim_calculando"));
            cargando.repaint();
            limpiar.setEnabled(false);
            jButton.setEnabled(false);
            consulta = new SwingWorker<Layer, Object>() {

                @Override
                protected Layer doInBackground() throws Exception {

                    publish(new Object[0]);

                    List<String> idRecursos = new ArrayList<String>();
                    List<Long> idZonas = new ArrayList<Long>();
                    for (Object o : recursos.getSelectedValues()) {
                        if (o instanceof Recurso) {
                            idRecursos.add(((Recurso) o).getIdentificador());
                        } else {
                            idRecursos.add(o.toString());
                        }
                    }
                    // for (Object o : zona.getSelectedValues()) {
                    // if (o instanceof Zona) {
                    // idZonas.add(((Zona) o).getId());
                    // }
                    // }

                    List<String> idIncidencias = new ArrayList<String>();
                    for (Object o : incidencias.getSelectedValues()) {
                        if (o instanceof Incidencia) {
                            idIncidencias.add(((Incidencia) o).getId().toString());
                        } else {
                            idIncidencias.add(o.toString());
                        }
                    }
                    if (soloUltimas.isSelected()) {
                        if (idRecursos.size() > 0) {
                            getUltimasPosiciones(Authentication.getUsuario().getNombreUsuario(), idRecursos,
                                    idZonas);
                        }
                        if (idIncidencias.size() > 0) {
                            getPosicionesIncidencias(Authentication.getUsuario().getNombreUsuario(),
                                    idIncidencias, idZonas);
                        }
                    } else {
                        if (idRecursos.size() > 0) {
                            getRutas(Authentication.getUsuario().getNombreUsuario(), idRecursos, getFechaIni(),
                                    getFechaFin());
                        }
                        if (idIncidencias.size() > 0) {
                            getPosicionesIncidencias(Authentication.getUsuario().getNombreUsuario(),
                                    idIncidencias, idZonas);
                        }
                    }
                    return null;
                }

                @Override
                protected void process(List<Object> chunks) {
                    super.process(chunks);
                    cleanLayers();
                    cargando.setIcon(LogicConstants.getIcon("anim_calculando"));
                    cargando.repaint();
                }

                @Override
                protected void done() {
                    HistoryMapViewer.getResultadoHistoricos().setSelected(true);
                    cargando.setIcon(LogicConstants.getIcon("48x48_transparente"));
                    cargando.repaint();
                }
            };
            consulta.execute();
        }
    });
    return jButton;
}

From source file:com.aw.swing.mvp.binding.component.BndSJTable.java

/**
 * Refresh the content of the JComponents
 *//*from w  w  w. j  a  v a2  s.c o m*/
public void refresh(final Object param) {
    if (refreshAbortable) {
        ProcessMsgBlocker.instance().showMessage("Procesando ...");
        //            final ProcessMsgBlocker msgBlocker = ProcessMsgBlocker.instance();
        //            final SearchMsgBlocker msgBlocker = SearchMsgBlocker.instance();
        SwingWorker swingWorker = new SwingWorker() {
            protected Object doInBackground() throws Exception {
                refreshInternal(param);
                return null;
            }

            protected void done() {
                //                    msgBlocker.close();
                ProcessMsgBlocker.instance().removeMessage();
            }
        };
        swingWorker.execute();
        if (SwingUtilities.isEventDispatchThread()) {
            //                msgBlocker.show();
            ProcessMsgBlocker.instance().showMessage("Procesando ...");
        } else {
            try {
                SwingUtilities.invokeAndWait(new Runnable() {
                    public void run() {
                        ProcessMsgBlocker.instance().showMessage("Procesando ...");
                        //                            msgBlocker.show();
                    }
                });
            } catch (Throwable e) {
                throw new AWSystemException("Problems refreshing the table:" + this, e);
            }
        }
    } else {
        if (SwingUtilities.isEventDispatchThread()) {
            refreshInternal(param);
        } else {
            try {
                SwingUtilities.invokeAndWait(new Runnable() {
                    public void run() {
                        refreshInternal(param);
                    }
                });
            } catch (Throwable e) {
                throw new AWSystemException("Problems refreshing the table:" + this, e);
            }
        }
    }
}

From source file:sk.uniza.fri.pds.spotreba.energie.gui.MainGui.java

private void jMenuItem8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem8ActionPerformed
    final ReportParams params = new ReportParams();
    int option = showUniversalInputDialog(params, "Ro?n sprva pre zkaznka", new Dimension(400, 80));
    if (option == JOptionPane.OK_OPTION) {
        new SwingWorker<List, RuntimeException>() {
            @Override// w w w  . j  a va2s.c  om
            protected List doInBackground() throws Exception {
                try {
                    return SeHistoriaService.getInstance().createLastYearReport(params);
                } catch (RuntimeException e) {
                    publish(e);
                    return null;
                }
            }

            @Override
            protected void done() {
                try {
                    List<String> data = get();
                    if (data != null) {
                        JOptionPane.showMessageDialog(null, "Export prebehol spene");
                    }
                } catch (InterruptedException | ExecutionException ex) {
                    Logger.getLogger(MainGui.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            @Override
            protected void process(List<RuntimeException> chunks) {
                if (chunks.size() > 0) {
                    showException("Chyba", chunks.get(0));
                }
            }

        }.execute();
    }
}

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

private void startMapReduceJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startMapReduceJButtonActionPerformed
    SwingWorker<Void, Void> swingWorker = new SwingWorker<Void, Void>() {
        @Override/* ww w  . ja v a2s. co  m*/
        protected Void doInBackground() throws Exception {
            disableGUI();
            String id = StringUtils.trimToNull(productIdJTextField.getText());
            String description = StringUtils.trimToNull(productDescriptionJTextField.getText());
            Integer year = getIntegerValue(yearJTextField);
            IntegerFilterOperator yearOperator = getIntegerFilterOperator(yearOperatorJComboBox);
            Integer month = getIntegerValue(monthJTextField);
            IntegerFilterOperator monthOperator = getIntegerFilterOperator(monthOperatorJComboBox);
            Integer day = getIntegerValue(dayJTextField);
            IntegerFilterOperator dayOperator = getIntegerFilterOperator(dayOperatorJComboBox);
            SaleFactFilter saleFactFilter = new SaleFactFilter(id, description, year, yearOperator, month,
                    monthOperator, day, dayOperator);
            JobRunner.getInstance().runJob(getAggregationLevel(), saleFactFilter);
            List<SaleFact> saleFacts = ReaderClient.getInstance().getSaleFacts();
            String[][] mapReduceResults = new String[saleFacts.size()][MAP_REDUCE_RESULTS_COLUMNS_NAMES.length];
            for (int i = 0; i < saleFacts.size(); i++) {
                SaleFact saleFact = saleFacts.get(i);
                mapReduceResults[i][0] = saleFact.getTimeDimension().getYear() != null
                        ? String.valueOf(saleFact.getTimeDimension().getYear())
                        : "";
                mapReduceResults[i][1] = saleFact.getTimeDimension().getMonth() != null
                        ? String.valueOf(saleFact.getTimeDimension().getMonth())
                        : "";
                mapReduceResults[i][2] = saleFact.getTimeDimension().getDay() != null
                        ? String.valueOf(saleFact.getTimeDimension().getDay())
                        : "";
                mapReduceResults[i][3] = String.valueOf(saleFact.getProductQuantity());
                mapReduceResults[i][4] = currencyFormatter.format(saleFact.getPrice());
                mapReduceResults[i][5] = saleFact.getProductDimension().getId();
                mapReduceResults[i][6] = saleFact.getProductDimension().getDescription();
            }
            mapReduceResultsTableDataModel.setDataVector(mapReduceResults, MAP_REDUCE_RESULTS_COLUMNS_NAMES);
            enableGUI();
            return null;
        }
    };
    swingWorker.execute();

}

From source file:edu.ku.brc.specify.tasks.subpane.images.ImagesPane.java

/**
 * /*w  w  w  . j  ava2s  . co m*/
 */
private void searchForRecordSetAttachments() {
    final String MEGS = "MEGS";
    final String STATUSBAR_NAME = "ImageSearchStatusBar";

    rowsVector.clear();
    items = recordSet.getOrderedItems();

    final int numItems = items.size();

    SwingWorker<Integer, Integer> backupWorker = new SwingWorker<Integer, Integer>() {
        @Override
        protected Integer doInBackground() throws Exception {
            final DBTableInfo ti = DBTableIdMgr.getInstance().getInfoById(recordSet.getDbTableId());

            boolean isAttachmentTableItself = ti.getTableId() == Attachment.getClassTableId();

            String sql;
            if (!isAttachmentTableItself) {
                sql = "SELECT a.AttachmentID, a.TableID, a.Title, a.AttachmentLocation, a.MimeType FROM attachment a "
                        + "INNER JOIN %sattachment coa ON a.AttachmentID = coa.AttachmentID "
                        + "WHERE coa.%s IN (%s) %s ORDER BY FIELD(%s, %s)";
            } else {
                sql = "SELECT a.AttachmentID, a.TableID, a.Title, a.AttachmentLocation, a.MimeType FROM attachment a "
                        + "WHERE AttachmentID IN (%s) ORDER BY FIELD(a.AttachmentID, %s)";
            }

            int batchSize = 500;
            int attchIndex = 0;
            int batches = (numItems / batchSize) + (numItems % batchSize == 0 ? 0 : 1);
            if (numItems < batchSize) {
                batchSize = numItems;
            }

            Statement stmt = null;
            try {
                stmt = DBConnection.getInstance().getConnection().createStatement();

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < batches; i++) {
                    firePropertyChange(MEGS, 0, i + 1);
                    sb.setLength(0);
                    for (int j = 0; j < batchSize && attchIndex < numItems; j++) {
                        RecordSetItemIFace rsi = items.get(attchIndex++);
                        if (j > 0)
                            sb.append(',');
                        sb.append(rsi.getRecordId().toString());
                    }

                    String filter = getFilterString();
                    if (StringUtils.isNotEmpty(filter)) {
                        filter = " AND " + filter;
                    }

                    String fullSQL;
                    if (!isAttachmentTableItself) {
                        fullSQL = String.format(sql, ti.getName(), ti.getIdColumnName(), sb.toString(), filter,
                                ti.getIdColumnName(), sb.toString());
                    } else {
                        fullSQL = String.format(sql, sb.toString(), filter, sb.toString());
                    }
                    log.debug(fullSQL);
                    ResultSet rs = stmt.executeQuery(fullSQL);
                    while (rs.next()) {
                        ImageDataItem imgDataItem = new ImageDataItem(rs.getInt(1), rs.getInt(2),
                                rs.getString(3), rs.getString(4), rs.getString(5));
                        rowsVector.add(imgDataItem);
                    }
                    rs.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (stmt != null)
                        stmt.close();
                } catch (Exception e) {
                }
            }
            return null;
        }

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

            getStatusBar().setProgressDone(STATUSBAR_NAME);
            clearSimpleGlassPaneMsg();

            if (rowsVector != null && rowsVector.size() > 0) {
                gridPanel.setItemList(rowsVector);
                JScrollPane sb = new JScrollPane(gridPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                        JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
                add(sb, BorderLayout.CENTER);

                ((AttachmentsTask) task).attachmentSearchDone(ImagesPane.this);

            } else {
                ((AttachmentsTask) task).attachmentSearchDone(null);
                writeTimedSimpleGlassPaneMsg(getNotFoundMessage());
            }
        }
    };

    final JStatusBar statusBar = getStatusBar();
    statusBar.setIndeterminate(STATUSBAR_NAME, true);

    writeSimpleGlassPaneMsg(getResourceString("ATTCH_SEARCH_IMGS"), 24);

    backupWorker.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            if (MEGS.equals(evt.getPropertyName())) {
                Integer value = (Integer) evt.getNewValue();
                int val = (int) (((double) value / (double) numItems) * 100.0);
                statusBar.setText(Integer.toString(val));//getLocalizedMessage("MySQLBackupService.BACKUP_MEGS", val));
            }
        }
    });
    backupWorker.execute();
}

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

/**
 * @param searchStr/*from   w w w. j  a v a 2 s .co  m*/
 * @param cbListener
 */
private void doSearchGenusSpecies(final String searchStr, final LMSearchCallbackListener cbListener) {
    UsageTracker.incrUsageCount("LM.GenSpSearch");

    updateMyDataUIState(false);

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

    SwingWorker<String, String> worker = new SwingWorker<String, String>() {
        @Override
        protected String doInBackground() throws Exception {
            HttpClient httpClient = new HttpClient();
            httpClient.getParams().setParameter("http.useragent", getClass().getName()); //$NON-NLS-1$
            httpClient.getParams().setParameter("http.socket.timeout", 15000);

            String genusSpecies = StringUtils.replace(searchStr, " ", "%20");
            String url = "http://www.lifemapper.org/hint/species/" + genusSpecies
                    + "?maxReturned=1000&format=json";
            //System.out.println(url);

            GetMethod getMethod = new GetMethod(url);
            try {
                httpClient.executeMethod(getMethod);
                return getMethod.getResponseBodyAsString();
            } catch (java.net.UnknownHostException uex) {
                //log.error(uex.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                UsageTracker.incrUsageCount("LM.GenSpSearchErr");
            }
            return null;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void done() {
            super.done();

            ArrayList<OccurrenceSetIFace> items = null;

            String errMsgKey = "LifeMapperTask.PROC_ERR";
            String responseString;
            try {
                responseString = get();
                //System.out.println(responseString);

                if (responseString != null) {
                    if (responseString.startsWith("None of the species")) {
                        errMsgKey = "LM_NO_LM_DATA";

                    } else if (responseString.startsWith("Search too broad")) {
                        errMsgKey = "LM_TOO_BROAD";

                    } else if (StringUtils.isNotEmpty(responseString)
                            && StringUtils.contains(responseString.toLowerCase(), "{")) {
                        JSONTokener tok = new JSONTokener(responseString);
                        while (tok.more()) {
                            JSONObject obj = (JSONObject) tok.nextValue();
                            JSONArray pointArray = (JSONArray) obj.get("columns");
                            Iterator<Object> iter = (Iterator<Object>) pointArray.iterator();
                            while (iter.hasNext()) {
                                JSONArray arrayObj = (JSONArray) iter.next();
                                //System.out.println(arrayObj);
                                Iterator<Object> iterInner = (Iterator<Object>) arrayObj.iterator();
                                while (iterInner.hasNext()) {
                                    JSONObject pObj = (JSONObject) iterInner.next();
                                    String binomial = (String) pObj.get("binomial");
                                    String gnSpName = (String) pObj.get("name");
                                    String numPoints = (String) pObj.get("numPoints");
                                    String occurrenceSet = (String) pObj.get("occurrenceSet");

                                    if (StringUtils.isNotEmpty(gnSpName) && StringUtils.isNotEmpty(numPoints)
                                            && StringUtils.isNotEmpty(occurrenceSet)) {
                                        try {
                                            int numPnts = Integer.parseInt(numPoints);
                                            int occurId = Integer.parseInt(occurrenceSet);
                                            if (numPnts > 0 && occurId > 0) {
                                                if (items == null) {
                                                    items = new ArrayList<OccurrenceSetIFace>();
                                                }
                                                items.add(new GenusSpeciesDataItem(
                                                        String.format("%s (%s)", gnSpName, numPoints),
                                                        occurrenceSet, binomial));
                                            }
                                        } catch (Exception ex) {
                                            // no op
                                        }
                                        errMsgKey = items == null || items.size() == 0 ? "LM_NO_LOCAL_DATA"
                                                : null;
                                    }
                                }
                            }
                        }
                    }
                }

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

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

            if (errMsgKey != null) {
                showErrorMsg(glassPane, errMsgKey);
                cbListener.noItems();

            } else {
                //System.out.println("Num Genus/Species: "+items.size());
                clearSimpleGlassPaneMsg();
                cbListener.itemsFound(items);
            }
        }
    };
    worker.execute();
}

From source file:com.dfki.av.sudplan.vis.VisualizationPanel.java

/**
 * Adds a GeoTiff file to the world wind model.
 *
 * @param file the {@link File} to add.// ww w  .  j a v  a2 s .c  o m
 * @throws IllegalArgumentException if file == null
 * @throws IOException
 */
public void addGeoTiffLayer(File file) throws IOException {
    if (file == null) {
        String msg = "file == null";
        log.error(msg);
        throw new IllegalArgumentException(msg);
    }

    final File geotiffFile = file;
    SwingWorker workerThread = new SwingWorker() {

        @Override
        protected Object doInBackground() throws Exception {
            SurfaceImageLayer layer = new SurfaceImageLayer();
            layer.setPickEnabled(false);
            layer.setValue(AVKey.DISPLAY_NAME, geotiffFile.getName());
            layer.addImage(geotiffFile.getAbsolutePath());
            ApplicationTemplate.insertBeforePlacenames(wwd, layer);
            return null;
        }
    };
    workerThread.execute();
}

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

private void calcGeoStats() {
    synchronized (this) {
        if (blockStatsUpdates)
            return;

        if (allCountriesRB.isSelected()) {
            if (!countriesCBX.isSelected()) {
                countriesTotalLabel.setText("");
                statesTotalLabel.setText("");
                return;
            }/*w w w. j av a  2s.c o  m*/
            if (!stateCBX.isSelected()) {
                statesTotalLabel.setText("");
            }
        } else {
            if (spCountriesCmbx.getSelectedIndex() < 1) {
                countriesTotalLabel.setText("");
                statesTotalLabel.setText("");
                return;
            }
            if (!spStatesCBX.isSelected()) {
                statesTotalLabel.setText("");
            }
        }

        SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
            Integer totalCountries = null;
            Integer totalStates = null;

            @Override
            protected Object doInBackground() throws Exception {
                boolean isAll = allCountriesRB.isSelected();
                int selInx = spCountriesCmbx.getSelectedIndex();

                String base = "SELECT COUNT(*) FROM geography WHERE GeographyCode IS NULL";

                totalCountries = (!isAll && selInx < 1) ? null
                        : getCountAsInt(base + " AND RankID = 200"
                                + (isAll ? "" : " AND GeographyID = " + countryIds.get(selInx)));

                if ((isAll && stateCBX.isSelected()) || (!isAll && spStatesCBX.isSelected())) {
                    String sql = base + " AND RankID = 300";
                    if (!isAll) {
                        sql += " AND ParentID = " + countryIds.get(selInx);
                    }
                    totalStates = getCountAsInt(sql);
                }
                return null;
            }

            @Override
            protected void done() {
                if (totalCountries != null) {
                    countriesTotalLabel.setText(totalCountries.toString());
                }
                if (totalStates != null) {
                    statesTotalLabel.setText(totalStates.toString());
                }
            }
        };
        worker.execute();
    }
}

From source file:sk.uniza.fri.pds.spotreba.energie.gui.MainGui.java

private void showLastYearChange(double factor) throws HeadlessException {
    final IncreasedSpendingStatisticParams params = new IncreasedSpendingStatisticParams();
    params.setDatumDo(new Date());
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.MONTH, -12);
    Date result = cal.getTime();/*from   ww  w .  j  a  v  a2  s.com*/
    params.setDatumOd(result);
    new SwingWorker<List, RuntimeException>() {
        @Override
        protected List doInBackground() throws Exception {
            try {
                return SeHistoriaService.getInstance().getIncreasedSpendingStatistics(params, factor);
            } catch (RuntimeException e) {
                publish(e);
                return null;
            }
        }

        @Override
        protected void done() {
            try {
                List data = get();
                showJTable(ZvysenieSpotreby.class, data);
            } catch (InterruptedException | ExecutionException ex) {
                Logger.getLogger(MainGui.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        @Override
        protected void process(List<RuntimeException> chunks) {
            if (chunks.size() > 0) {
                showException("Chyba", chunks.get(0));
            }
        }

    }.execute();
}