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:org.usfirst.frc.team2084.neuralnetwork.HeadingNeuralNetworkTrainer.java

private void saveNetwork() {
    if (saveFileChooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
        File saveFile = saveFileChooser.getSelectedFile();

        new SwingWorker<Void, Void>() {

            @Override/*from w w w.  j av  a2 s.  com*/
            protected Void doInBackground() throws Exception {
                synchronized (network) {
                    new Data(network).save(saveFile);
                }

                return null;
            }

            @Override
            protected void done() {
            }
        }.execute();
    }
}

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

/**
 * @param fii/*from w w  w  . ja  v a2 s. c o m*/
 */
private void checkForAddrs(final FindItemInfo fii) {
    System.out.println("\ncheckForAddrs (async)");

    SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
        boolean hasAddrs = false;

        @Override
        protected Object doInBackground() throws Exception {
            String inClause = fii.getInClause(true);
            String sql = String.format("SELECT COUNT(*) FROM address WHERE AgentID IN %s", inClause);
            hasAddrs = BasicSQLUtils.getCountAsInt(sql) > 0;
            return null;
        }

        @Override
        protected void done() {
            if (hasAddrs) {
                /*AddressCleanupDlg addrCleanup = new AddressCleanupDlg(fii); // NOTE: SQL is done on UI thread
                addrCleanup.fillModel();
                        
                if (!addrCleanup.isSingle())
                {
                    addrCleanup.pack();
                    addrCleanup.setSize(800, 500);
                    UIHelper.centerWindow(addrCleanup);
                    addrCleanup.setVisible(true);
                    isContinuing = !addrCleanup.isCancelled();
                }
                        
                List<AddrInfo> addrIdList = addrCleanup.getAddrIds();
                        
                if (doUpdates)
                {
                    if (addrIdList != null && addrIdList.size() > 0)
                    {
                   if (!cleanupAddresses(fii, addrIdList))
                   {
                       showError(String.format("There was an error cleaning up addresses for agent'%s'", fii.getValue().toString()));
                       isContinuing = false;
                   }
                    }
                }*/

                MultipleRecordCleanupDlg mrcDlg = null;
                try {
                    isSkipping = false;
                    MultipleRecordComparer mrc = new MultipleRecordComparer(fii, Agent.getClassTableId(),
                            Address.getClassTableId(), AgentVariant.getClassTableId()
                    //AccessionAgent.getClassTableId()
                    //AgentSpecialty.getClassTableId(),
                    //AgentGeography.getClassTableId()
                    );
                    mrc.setSingleRowIncluded(false, false, false, false);
                    mrc.addDisplayColumn("Agent's Name");

                    mrc.loadData();

                    if (mrc.hasColmnsOfDataThatsDiff() || mrc.hasKidsDataThatsDiff()) {
                        mrcDlg = new MultipleRecordCleanupDlg(mrc, "Agent Cleanup");
                        mrcDlg.createUI();
                        if (!mrcDlg.isSingle()) {
                            mrcDlg.pack();
                            mrcDlg.setSize(800, 500);
                            UIHelper.centerWindow(mrcDlg);
                            mrcDlg.toFront();
                            prgDlg.toBack();
                            mrcDlg.setVisible(true);
                            prgDlg.toFront();
                            isContinuing = !mrcDlg.isCancelled();
                            isSkipping = mrcDlg.getBtnPressed() == CustomDialog.APPLY_BTN;
                        }

                        if (isContinuing) {
                            MergeInfo mainItem = mrcDlg.getMainMergedInfo();
                            List<MergeInfo> kidItems = mrcDlg.getKidsMergedInfo();
                            if (!cleanupMerges(Agent.getClassTableId(), mainItem, kidItems)) {
                                String msg = String.format(
                                        "There was an error cleaning up addresses for agent '%s'",
                                        fii.getValue().toString());
                                showProcessingMessage(msg);
                                log.error(msg);
                                isContinuing = false;
                            }
                            if (!deleteMerges(Agent.getClassTableId(), mainItem, kidItems)) {
                                String msg = String.format(
                                        "There was an error cleaning up addresses for agent '%s'",
                                        fii.getValue().toString());
                                showProcessingMessage(msg);
                                log.error(msg);
                                isContinuing = false;
                            }
                        }
                    } else if (mrc.hasRecords()) {
                        log.debug("Here");
                    } else {
                        isContinuing = true;
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

                if (isContinuing) {
                    prgDlg.toFront();
                    doMergeOfAgents(fii);
                } else {
                    prgDlg.setVisible(false);
                    prgDlg.dispose();
                }
            } else {
                doMergeOfAgents(fii);
            }
        }
    };
    worker.execute();
}

From source file:com.clough.android.adbv.view.MainFrame.java

private void refreshDatabase() {
    inputQuery = "";
    invalidateInputOutput();//from   ww  w.j  av  a  2 s  .co m
    new SwingWorker<Void, Void>() {

        @Override
        protected Void doInBackground() throws Exception {
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
            }
            try {
                String tableNames = MainFrame.this.ioManager.getTableNames();
                tableNameJSONArray = new JSONArray(tableNames);
            } catch (IOManagerException ex) {
                showDeviceDisconnectedDialog();
            }
            return null;
        }

        @Override
        protected void done() {
            closeProgressDialog();
        }

    }.execute();
    showProgressDialog(true, 0, "Waiting for table list");

    tableInfoTree.removeAll();
    tableInfoTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    final DefaultMutableTreeNode databaseDMTN = new DefaultMutableTreeNode(databaseName);
    tableInfoTree.setModel(new DefaultTreeModel(databaseDMTN));
    new SwingWorker<Void, Void>() {
        @Override
        protected Void doInBackground() throws Exception {
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
            }
            try {
                tables = new String[tableNameJSONArray.length()];
                queries = new String[tableNameJSONArray.length()];
                columns = new String[tableNameJSONArray.length()][];
                columnInfos = new String[tableNameJSONArray.length()][][];
                for (int i = 0; i < tableNameJSONArray.length(); i++) {
                    tables[i] = tableNameJSONArray.getJSONObject(i).getString("name");
                    DefaultMutableTreeNode tableDMTN = new DefaultMutableTreeNode(tables[i]);
                    databaseDMTN.add(tableDMTN);
                    queries[i] = tableNameJSONArray.getJSONObject(i).getString("sql");
                    String tableColumnInfo = MainFrame.this.ioManager.getTableColumnInfo(tables[i]);
                    JSONArray columnJSONArray = new JSONArray(tableColumnInfo);
                    columns[i] = new String[columnJSONArray.length()];
                    columnInfos[i] = new String[columnJSONArray.length()][];
                    for (int j = 0; j < columnJSONArray.length(); j++) {
                        JSONObject columnJSONObject = columnJSONArray.getJSONObject(j);
                        columns[i][j] = columnJSONObject.getString("name");
                        columnInfos[i][j] = new String[4];
                        DefaultMutableTreeNode columnDMTN = new DefaultMutableTreeNode(columns[i][j]);
                        columnInfos[i][j][0] = "Column ID : " + String.valueOf(columnJSONObject.getInt("cid"));
                        columnDMTN.add(new DefaultMutableTreeNode(columnInfos[i][j][0]));
                        columnInfos[i][j][1] = "Type : " + columnJSONObject.getString("type");
                        columnDMTN.add(new DefaultMutableTreeNode(columnInfos[i][j][1]));
                        columnInfos[i][j][2] = "Def value : "
                                + String.valueOf(columnJSONObject.getString("dflt_value"));
                        columnDMTN.add(new DefaultMutableTreeNode(columnInfos[i][j][2]));
                        columnInfos[i][j][3] = "Not NULL : "
                                + String.valueOf((columnJSONObject.getInt("notnull") == 1));
                        columnDMTN.add(new DefaultMutableTreeNode(columnInfos[i][j][3]));
                        tableDMTN.add(columnDMTN);
                    }
                    databaseDMTN.add(tableDMTN);
                    waitingDialog.incrementProgressBar();
                }
            } catch (IOManagerException ex) {
                showDeviceDisconnectedDialog();
            }
            return null;
        }

        @Override
        protected void done() {
            closeProgressDialog();
        }

    }.execute();
    showProgressDialog(false, tableNameJSONArray.length(),
            "Getting info of " + tableNameJSONArray.length() + " tables");
    tableInfoTree.expandPath(new TreePath((TreeNode) tableInfoTree.getModel().getRoot()));
    tableNameJSONArray = null;

}

From source file:edu.ku.brc.specify.tools.schemalocale.SchemaToolsDlg.java

/**
 * //w ww  .  ja va2  s .  co m
 */
@SuppressWarnings("unchecked")
protected void exportSchemaLocales() {
    FileDialog dlg = new FileDialog(((Frame) UIRegistry.getTopWindow()), getResourceString("Save"),
            FileDialog.SAVE);
    dlg.setVisible(true);

    String fileName = dlg.getFile();
    if (fileName != null) {
        final File outFile = new File(dlg.getDirectory() + File.separator + fileName);
        //final File    outFile = new File("xxx.xml");

        final SimpleGlassPane glassPane = new SimpleGlassPane(getResourceString("SL_EXPORT_SCHEMA"), 18);
        glassPane.setBarHeight(12);
        glassPane.setFillColor(new Color(0, 0, 0, 85));

        setGlassPane(glassPane);
        glassPane.setVisible(true);

        SwingWorker<Integer, Integer> backupWorker = new SwingWorker<Integer, Integer>() {
            @Override
            protected Integer doInBackground() throws Exception {

                DataProviderSessionIFace session = null;
                try {
                    session = DataProviderFactory.getInstance().createSession();

                    int dispId = AppContextMgr.getInstance().getClassObject(Discipline.class).getDisciplineId();
                    String sql = String.format(
                            "FROM SpLocaleContainer WHERE disciplineId = %d AND schemaType = %d", dispId,
                            schemaType);
                    List<SpLocaleContainer> spContainers = (List<SpLocaleContainer>) session.getDataList(sql);
                    try {
                        FileWriter fw = new FileWriter(outFile);

                        //fw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<vector>\n");
                        fw.write("<vector>\n");

                        BeanWriter beanWriter = new BeanWriter(fw);
                        XMLIntrospector introspector = beanWriter.getXMLIntrospector();
                        introspector.getConfiguration().setWrapCollectionsInElement(true);
                        beanWriter.getBindingConfiguration().setMapIDs(false);
                        beanWriter.setWriteEmptyElements(false);

                        beanWriter.enablePrettyPrint();

                        double step = 100.0 / (double) spContainers.size();
                        double total = 0.0;
                        for (SpLocaleContainer container : spContainers) {
                            // force Load of lazy collections
                            container.getDescs().size();
                            container.getNames().size();

                            // Leaving this Code as an example of specifying the bewtixt file.
                            /*InputStream inputStream = Specify.class.getResourceAsStream("datamodel/SpLocaleContainer.betwixt");
                            //InputStream inputStream = Specify.class.getResourceAsStream("/edu/ku/brc/specify/tools/schemalocale/SpLocaleContainer.betwixt");
                            InputSource inputSrc    = new InputSource(inputStream); 
                            beanWriter.write(container, inputSrc);
                            inputStream.close(); */

                            beanWriter.write(container);

                            total += step;
                            firePropertyChange("progress", 0, (int) total);
                        }

                        fw.write("</vector>\n");
                        fw.close();

                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

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

                } finally {
                    if (session != null) {
                        session.close();
                    }
                }

                return null;
            }

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

                glassPane.setVisible(false);
            }
        };

        backupWorker.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(final PropertyChangeEvent evt) {
                if (evt.getPropertyName().equals("progress")) {
                    glassPane.setProgress((Integer) evt.getNewValue());
                }
            }
        });
        backupWorker.execute();
    }
}

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

/**
 * @param urlStr/*from w  w  w  . j  av  a2 s  .co  m*/
 * @param listener
 */
public static void getImageFromWeb(final String urlStr, final BufferedImageFetcherIFace listener) {
    //System.out.println(urlStr);

    SwingWorker<BufferedImage, BufferedImage> worker = new SwingWorker<BufferedImage, BufferedImage>() {
        @Override
        protected BufferedImage doInBackground() throws Exception {
            try {
                URL url = new URL(urlStr);
                return ImageIO.read(url);

            } catch (IOException e) {

            }
            return null;
        }

        @Override
        protected void done() {
            try {
                BufferedImage img = get();
                listener.imageFetched(img);
                return;

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

            super.done();
        }
    };
    worker.execute();
}

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

public void doReloadResource() {
    final int selectedRow = resourceTable.getSelectedRow();

    if (selectedRow >= 0) {
        if (getFrame().isSaveEnabled()) {
            getFrame().alertWarning(getFrame(), "You must save before reloading any resources.");
            return;
        }// www.  j  a v a 2 s. c  o  m

        if (!getFrame().alertOption(getFrame(),
                "<html>Libraries associated with this resource will be reloaded.<br/>Any channels / connectors using those libraries will be<br/>affected. Also, a maximum of 1000 files may be loaded into<br/>a directory resource, with additional files being skipped.<br/>Are you sure you wish to continue?</html>")) {
            return;
        }

        final String workingId = getFrame().startWorking("Reloading resource...");
        final String resourceId = ((ResourceProperties) resourceTable.getModel().getValueAt(selectedRow,
                PROPERTIES_COLUMN)).getId();

        SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

            @Override
            public Void doInBackground() throws ClientException {
                getFrame().mirthClient.reloadResource(resourceId);
                return null;
            }

            @Override
            public void done() {
                try {
                    get();

                    if (resourceTable.getSelectedRow() == selectedRow && currentPropertiesPanel != null) {
                        ResourceProperties properties = (ResourceProperties) resourceTable.getModel()
                                .getValueAt(selectedRow, PROPERTIES_COLUMN);
                        properties.setName(
                                (String) resourceTable.getModel().getValueAt(selectedRow, NAME_COLUMN));
                        properties.setIncludeWithGlobalScripts((Boolean) resourceTable.getModel()
                                .getValueAt(selectedRow, GLOBAL_SCRIPTS_COLUMN));
                        currentPropertiesPanel.fillProperties(properties);
                        currentPropertiesPanel.setProperties(properties);
                    }
                } catch (Throwable t) {
                    if (t instanceof ExecutionException) {
                        t = t.getCause();
                    }
                    getFrame().alertThrowable(getFrame(), t, "Error reloading resource: " + t.toString());
                } finally {
                    getFrame().stopWorking(workingId);
                }
            }
        };

        worker.execute();
    }
}

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

private void servisStatsMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_servisStatsMenuItemActionPerformed
    new SwingWorker<List, RuntimeException>() {
        @Override/*from   w w  w.j av a2 s.c  o m*/
        protected List doInBackground() throws Exception {
            try {
                return SeServisService.getInstance().getServiceStatistics();
            } catch (RuntimeException e) {
                publish(e);
                return null;
            }
        }

        @Override
        protected void done() {
            try {
                List data = get();
                showJTable(StatistikaServisov.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();

}

From source file:edu.ku.brc.specify.tasks.CleanupToolsTask.java

/**
 * /*  w ww  .  ja va 2 s  . c  om*/
 */
private void updateNames(final Vector<AgentNameCleanupParserDlg.DataItem> dataItemsList) {
    final String PRC = "PROCESS";
    final SimpleGlassPane glassPane = UIRegistry.writeSimpleGlassPaneMsg("Processing agents...", 24);

    //prgDlg = new ProgressDialog(getResourceString("CLNUP_AG_PRG_TITLE"), true, false);
    //prgDlg.getProcessProgress().setIndeterminate(true);
    //prgDlg.setDesc(getResourceString("CLNUP_AG_INIT_MSG"));
    //UIHelper.centerAndShow(prgDlg);

    final SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
        double tot = 0; // 1 -> 100
        double step = 1.0;
        int cnt = 0;

        @Override
        protected Object doInBackground() throws Exception {
            step = 100.0 / dataItemsList.size();

            Connection conn = null;
            PreparedStatement pStmt = null;
            try {
                String sql = "UPDATE agent SET LastName=?, FirstName=?,MiddleInitial=? WHERE AgentID = ?";
                conn = DBConnection.getInstance().createConnection();
                pStmt = conn.prepareStatement(sql);

                for (DataItem di : dataItemsList) {
                    if (di.isIncluded()) {
                        setColumn(pStmt, 1, di.getLastName());
                        setColumn(pStmt, 2, di.getFirstName());
                        setColumn(pStmt, 3, di.getMidName());
                        pStmt.setInt(4, di.getAgentId());

                        if (pStmt.executeUpdate() != 1) {
                            log.error(String.format("Error updating AgentID %d", di.getAgentId()));
                        }
                    }

                    tot += step;
                    if (((int) tot) > cnt) {
                        cnt = (int) tot;
                        firePropertyChange(PRC, -1, cnt);
                    }
                }
                dataItemsList.clear();

            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    if (pStmt != null)
                        pStmt.close();
                    if (conn != null)
                        conn.close();

                } catch (SQLException ex) {
                }
            }
            return null;
        }

        @Override
        protected void done() {
            UIRegistry.clearSimpleGlassPaneMsg();
            UIRegistry.showLocalizedMsg("Done.");
        }
    };
    worker.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            if (PRC.equals(evt.getPropertyName())) {
                glassPane.setProgress((Integer) evt.getNewValue());
            }
        }
    });
    worker.execute();
}

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

public void setAvaliableIncidences(Collection<Object> res) {
    avaliableIncidences = new Vector<Object>(res);
    Collections.sort(avaliableIncidences, comparator);

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

        @Override/*w w w.jav a  2s. co m*/
        protected Object doInBackground() throws Exception {
            return null;
        }

        @Override
        protected void done() {
            super.done();
            if (!isComboIncidencesShowing) {
                Object selected = incidences.getSelectedItem();
                incidences.removeAllItems();
                for (Object o : avaliableIncidences) {
                    incidences.addItem(o);
                }
                incidences.setSelectedItem(selected);
            }
            if (!isComboIncidencesShowing)
                incidences.updateUI();
        }
    };
    sw.execute();
}

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

private void updateStatus() {
    final String workingId = parent.startWorking("Refreshing status...");

    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        @Override/*from  www . j  a  v  a2 s  .  c o  m*/
        protected Void doInBackground() {
            try {
                Map<String, String> status = parent.mirthClient.getServlet(DataPrunerServletInterface.class)
                        .getStatusMap();
                currentStateTextLabel.setText(status.get("currentState"));
                currentProcessTextLabel.setText(status.get("currentProcess"));
                lastProcessTextLabel.setText(status.get("lastProcess"));

                String nextProcess = "Not scheduled";
                if (yesEnabledRadio.isSelected()) {
                    nextProcess = status.get("nextProcess");
                }
                nextProcessTextLabel.setText(nextProcess);

                if (status.get("isRunning").equals("false")) {
                    currentStateTextLabel.setForeground(INACTIVE_STATUS_COLOR);
                    setStartTaskVisible(true);
                    setStopTaskVisible(false);
                } else {
                    currentStateTextLabel.setForeground(ACTIVE_STATUS_COLOR);
                    setStartTaskVisible(false);
                    setStopTaskVisible(true);
                }
            } catch (ClientException e) {
                currentStateTextLabel.setText("Unknown");
                currentStateTextLabel.setForeground(UNKNOWN_STATUS_COLOR);
                currentProcessTextLabel.setText("");
                lastProcessTextLabel.setText("");
                nextProcessTextLabel.setText("");
                setStartTaskVisible(false);
                setStopTaskVisible(false);
                parent.alertThrowable(parent, e,
                        "An error occurred while attempting to retrieve the status of the data pruner.");
            }

            return null;
        }

        @Override
        public void done() {
            parent.stopWorking(workingId);
            refreshing.set(false);
        }
    };

    worker.execute();
}