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.rapidminer.gui.new_plotter.engine.jfreechart.JFreeChartPlotEngine.java

/**
 * Trigger an update of the {@link JFreeChart} that is stored in the {@link ChartPanel}. The
 * update is performed by using a {@link SwingWorker} thread. First the new Chart is created and
 * afterwards the new chart is stored in the {@link ChartPanel}.
 * /*from w w  w.j  a  va  2  s .  co  m*/
 * @param informPlotConfigWhenDone
 *            should inform the {@link PlotConfiguration} that the worker thread is done?
 */
private synchronized void updateChartPanelChart(final boolean informPlotConfigWhenDone) {
    updatingChart.getAndSet(true);

    StaticDebug.debug("######################### STARTING CHART UPDATE ######################");

    SwingWorker updateChartWorker = new SwingWorker<JFreeChart, Void>() {

        @Override
        public JFreeChart doInBackground() throws Exception {
            try {
                if (!isPlotInstanceValid()) {
                    return null;
                }
                try {
                    invalidateCache();
                    JFreeChart createdChart = createChart();
                    updateLegendItems();
                    checkWarnings();
                    currentChartIsValid = true;
                    return createdChart;
                } catch (ChartPlottimeException e) {
                    handlePlottimeException(e);
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
                SwingTools.showFinalErrorMessage("generic_plotter_error", e, true, new Object[] {});
                handlePlottimeException(new ChartPlottimeException("generic_plotter_error"));
                return null;
            }
        }

        @Override
        public void done() {
            try {
                JFreeChart chart = null;
                try {
                    chart = get(60, TimeUnit.SECONDS);
                    updatingChartPanelChartDone();
                } catch (Exception e) {
                    updatingChartPanelChartDone();
                    e.printStackTrace();
                    handlePlottimeException(new ChartPlottimeException("generic_plotter_error"));
                    return;
                }
                if (chart == null) {
                    currentChartIsValid = false;
                    chart = new JFreeChart(new CategoryPlot());
                }
                updateChartPanel(chart);

                // informs plotConfig that the repaint event has been processed
                if (informPlotConfigWhenDone) {
                    plotInstance.getMasterPlotConfiguration().plotConfigurationChangeEventProcessed();
                }
            } catch (Exception e) {
                e.printStackTrace();
                SwingTools.showFinalErrorMessage("generic_plotter_error", e);
            }

        }

    };

    updateChartWorker.execute();
}

From source file:com.mirth.connect.client.ui.browsers.event.EventBrowser.java

public void loadPageNumber(final int pageNumber) {
    final String workingId = parent.startWorking("Loading page...");

    if (worker != null && !worker.isDone()) {
        parent.mirthClient.getServerConnection().abort(getAbortOperations());
        worker.cancel(true);/*from  ww w .  j a v a2 s  .co m*/
    }

    filterButton.setEnabled(false);
    nextPageButton.setEnabled(false);
    previousPageButton.setEnabled(false);
    countButton.setEnabled(false);
    pageGoButton.setEnabled(false);

    // Give focus to the event table since these buttons will lose focus. That way the user can also immediately use the arrow keys after a search.
    eventTable.requestFocus();

    worker = new SwingWorker<Void, Void>() {
        private boolean foundItems = false;
        private int retrievedPageNumber = 1;

        public Void doInBackground() {

            try {
                foundItems = events.loadPageNumber(pageNumber);
            } catch (Throwable t) { // catch Throwable in case the client runs out of memory

                if (t.getMessage().contains("Java heap space")) {
                    parent.alertError(parent,
                            "There was an out of memory error when trying to retrieve events.\nIncrease your heap size or decrease your page size and search again.");
                } else if (t instanceof RequestAbortedException) {
                    // The client is no longer waiting for the search request
                } else {
                    parent.alertThrowable(parent, t);
                }
                cancel(true);
            }

            return null;
        }

        public void done() {
            if (!isCancelled()) {
                boolean enableCountButton = (events.getItemCount() == null);

                deselectRows();

                if (foundItems) {

                    // if there are no results for pageNumber, loadPageNumber will recursively check previous pages
                    // so we must get the retrievedPageNumber from events to use below.
                    retrievedPageNumber = events.getPageNumber();
                    pageNumberField.setText(String.valueOf(retrievedPageNumber));

                    updateEventTable(events);

                    if (!events.hasNextPage()) {
                        events.setItemCount(
                                new Long(((retrievedPageNumber - 1) * events.getPageSize()) + events.size()));
                        enableCountButton = false;
                    }
                } else {
                    if (eventTable != null) {
                        RefreshTableModel model = (RefreshTableModel) eventTable.getModel();
                        model.refreshDataVector(new Object[0][0]);
                    }

                    events.setItemCount(new Long((retrievedPageNumber - 1) * events.getPageSize()));
                    enableCountButton = false;
                    pageNumberField.setText("0");
                }

                updatePagination();

                if (enableCountButton) {
                    countButton.setEnabled(true);
                }
                filterButton.setEnabled(true);
            }
            parent.stopWorking(workingId);
        }
    };

    worker.execute();
}

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

/**
 * /*from   w w w .  j av  a 2  s  . co  m*/
 */
public void createDB() {
    getValues(properties);

    final String databaseName = dbNameTxt.getText();
    final String dbUserName = usernameTxt.getText();
    final String dbPwd = passwordTxt.getText();
    final String hostName = hostNameTxt.getText();

    if (isMobile()) {
        DBConnection.clearMobileMachineDir();
        File tmpDir = DBConnection.getMobileMachineDir(databaseName);
        setEmbeddedDBPath(tmpDir.getAbsolutePath());
    }

    final DatabaseDriverInfo driverInfo = (DatabaseDriverInfo) drivers.getSelectedItem();
    String connStrInitial = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, hostName,
            databaseName, dbUserName, dbPwd, driverInfo.getName());
    //System.err.println(connStrInitial);

    DBConnection.checkForEmbeddedDir("createDB - " + connStrInitial);

    DBConnection.getInstance().setDriverName(driverInfo.getName());
    DBConnection.getInstance().setServerName(hostName);

    VerifyStatus status = verifyDatabase(properties);
    if ((isOK == null || !isOK) && status == VerifyStatus.OK) {
        progressBar.setIndeterminate(true);
        progressBar.setVisible(true);

        label.setText(getResourceString("CONN_DB"));

        setUIEnabled(false);

        DatabasePanel.this.label.setForeground(Color.BLACK);

        SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
            /* (non-Javadoc)
             * @see javax.swing.SwingWorker#doInBackground()
             */
            @Override
            protected Object doInBackground() throws Exception {
                isOK = false;

                DBMSUserMgr mgr = DBMSUserMgr.getInstance();

                boolean dbmsOK = false;
                if (driverInfo.isEmbedded()) {
                    if (checkForProcesses) {
                        SpecifyDBSecurityWizardFrame.checkForMySQLProcesses();
                        checkForProcesses = false;
                    }

                    if (isMobile()) {
                        File mobileTmpDir = DBConnection.getMobileMachineDir();
                        if (!mobileTmpDir.exists()) {
                            if (!mobileTmpDir.mkdirs()) {
                                System.err.println(
                                        "Dir[" + mobileTmpDir.getAbsolutePath() + "] didn't get created!");
                                // throw exception
                            }
                            DBConnection.setCopiedToMachineDisk(true);
                        }
                    }

                    String newConnStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open,
                            hostName, databaseName, dbUserName, dbPwd, driverInfo.getName());
                    if (driverInfo.isEmbedded()) {
                        //System.err.println(newConnStr);
                        try {
                            Class.forName(driverInfo.getDriverClassName());

                            // This call will create the database if it doesn't exist
                            DBConnection testDB = DBConnection.createInstance(driverInfo.getDriverClassName(),
                                    driverInfo.getDialectClassName(), databaseName, newConnStr, dbUserName,
                                    dbPwd);
                            testDB.getConnection(); // Opens the connection

                            if (testDB != null) {
                                testDB.close();
                            }
                            dbmsOK = true;

                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                        DBConnection.getInstance().setDatabaseName(null);
                    }
                } else if (mgr.connectToDBMS(dbUserName, dbPwd, hostName)) {
                    mgr.close();
                    dbmsOK = true;
                }

                if (dbmsOK) {
                    firePropertyChange(PROPNAME, 0, 1);

                    try {
                        SpecifySchemaGenerator.generateSchema(driverInfo, hostName, databaseName, dbUserName,
                                dbPwd); // false means create new database, true means update

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

                        firePropertyChange(PROPNAME, 0, 2);

                        // tryLogin sets up DBConnection
                        if (UIHelper.tryLogin(driverInfo.getDriverClassName(), driverInfo.getDialectClassName(),
                                dbNameTxt.getText(), connStr, dbUserName, dbPwd)) {

                            if (!checkEngineCharSet(properties)) {
                                return false;
                            }
                            isOK = true;

                            firePropertyChange(PROPNAME, 0, 3);

                            Thumbnailer thumb = Thumbnailer.getInstance();
                            File thumbFile = XMLHelper.getConfigDir("thumbnail_generators.xml");
                            thumb.registerThumbnailers(thumbFile);
                            thumb.setQuality(.5f);
                            thumb.setMaxSize(128, 128);

                            File attLoc = getAppDataSubDir("AttachmentStorage", true);
                            AttachmentManagerIface attachMgr = new FileStoreAttachmentManager(attLoc);
                            AttachmentUtils.setAttachmentManager(attachMgr);
                            AttachmentUtils.setThumbnailer(thumb);

                        } else {
                            errorKey = "NO_LOGIN_ROOT";
                        }
                    } catch (Exception ex) {
                        errorKey = "DB_UNRECOVERABLE";
                    }
                } else {
                    errorKey = "NO_CONN_ROOT";
                    mgr.close();
                }
                return null;
            }

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

                setUIEnabled(true);

                progressBar.setIndeterminate(false);
                progressBar.setVisible(false);

                updateBtnUI();

                if (isOK) {
                    label.setText(getResourceString("DB_CREATED"));
                    setUIEnabled(false);

                } else {
                    label.setText(getResourceString(errorKey != null ? errorKey : "ERR_CRE_DB"));
                    showLocalizedError(errorKey != null ? errorKey : "ERR_CRE_DB");
                }
            }
        };

        worker.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(final PropertyChangeEvent evt) {
                if (PROPNAME.equals(evt.getPropertyName())) {
                    String key = null;
                    switch ((Integer) evt.getNewValue()) {
                    case 1:
                        key = "BLD_SCHEMA";
                        break;
                    case 2:
                        key = "DB_FRST_LOGIN";
                        break;
                    case 3:
                        key = "BLD_CACHE";
                        break;
                    default:
                        break;
                    }
                    if (key != null) {
                        DatabasePanel.this.label.setText(getResourceString(key));
                    }
                }
            }
        });
        worker.execute();

    } else if (status == VerifyStatus.ERROR) {
        errorKey = "NO_LOGIN_ROOT";
        DatabasePanel.this.label.setText(getResourceString(errorKey));
        DatabasePanel.this.label.setForeground(Color.RED);

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                getTopWindow().pack();
            }
        });
    }
}

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

private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
    final StatistikaSpotriebParams params = new StatistikaSpotriebParams();
    int option = showUniversalInputDialog(params, "tatistika poda typu a kategrie");
    if (option == JOptionPane.OK_OPTION) {
        new SwingWorker<List, RuntimeException>() {
            @Override/*from   w w w  . j a  va2s. com*/
            protected List doInBackground() throws Exception {
                try {
                    return SeHistoriaService.getInstance().getOveralStatistics(params);
                } catch (RuntimeException e) {
                    publish(e);
                    return null;
                }
            }

            @Override
            protected void done() {
                try {
                    List data = get();
                    showJTable(CelkovaStatistika.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:org.eumetsat.metop.visat.SounderInfoView.java

private void updateEarthLocationFields(final Ifov selectedIfov, final EpsFile epsFile) {
    final SwingWorker<GeoPos, Object> worker = new SwingWorker<GeoPos, Object>() {
        @Override/*from ww w. j  ava2 s .  c o m*/
        protected GeoPos doInBackground() throws Exception {
            return readEarthLocation(epsFile, selectedIfov);
        }

        @Override
        protected void done() {
            try {
                final GeoPos geoPos = get();
                lonTextField.setText(geoPos.getLonString());
                latTextField.setText(geoPos.getLatString());
            } catch (InterruptedException e) {
                clearEarthLocationFields(IO_ERROR);
            } catch (ExecutionException e) {
                clearEarthLocationFields(IO_ERROR);
            }
        }
    };
    worker.execute();
}

From source file:fr.free.hd.servers.gui.FaceView.java

private void updateLabel() {
    ApplicationWindow aw = Application.instance().getActiveWindow();
    final ProgressMonitor pm = aw.getStatusBar().getProgressMonitor();
    pm.taskStarted("Rendering picture", -1);
    SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {
        //protected Object construct() in SpringRC's SwingWorker!  
        protected Object doInBackground() {
            // now my long task and the progress indication  
            if (position != null) {
                Phonem phonem = new Phonem("Demo", kind, position, MouthVowelEnum.MOUTH_VOWEL_A);
                FaceGeneratorHelper.initialWidthSize = 400;
                FaceGeneratorHelper.ClearCache();
                Image image = FaceGeneratorHelper.Create(phonem, face, pm);
                lblFace.setIcon(new ImageIcon(image));
            }//from   w ww. ja v a2s  .  c o  m
            return null;
        }

        //protected void finished()  
        @Override
        protected void done() {
            // all of the following code will be called on the Event Dispatching Thread  
            pm.done();
        }
    };
    //sw.start();  
    //sw.clear(); // reuse would be possible with SpringRC's SwingWorker!  
    sw.execute();
}

From source file:it.illinois.adsc.ema.softgrid.monitoring.ui.SPMainFrame.java

@Override
public void stopIEDServers() {
    SwingWorker iedWorker = new SwingWorker() {
        @Override//from   w w w .j  a v  a2s .c  om
        protected Object doInBackground() throws Exception {
            messageHandler.addLogMessage("Stop all operations...!");
            stopMonitor();
            messageHandler.addLogMessage("Close all windows...!");
            windowClosing(null);
            messageHandler.addLogMessage("exit IED server...!");
            setVisible(false);
            messageHandler.addLogMessage("Stop all IED threads...!");
            SoftGridController.killAll();
            System.exit(0);
            return null;
        }
    };
    iedWorker.execute();
}

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

/**
 * @param genusSpecies/*from w  w  w .j  a va2s .  co m*/
 */
private void doSearchSpecifyData(final String genusSpecies) {
    UsageTracker.incrUsageCount("LM.MyDataSearch");

    myDataTaxa = genusSpecies;

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

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

            return addLocalData(genusSpecies);
        }

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

            Integer cnt = null;
            try {
                cnt = get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            if (cnt == null || cnt == 0) {
                writeTimedSimpleGlassPaneMsg(getResourceString("LM_NO_LOCAL_DATA"), null, Color.RED,
                        GLASS_FONT_SIZE, true, (int) ((double) getSize().height * 0.25));
                UsageTracker.incrUsageCount("LM.NoMyData");
            } else {
                String msg = UIRegistry.getFormattedResStr("LM_MYDATA_FND", cnt, myDataTaxa);
                writeTimedSimpleGlassPaneMsg(msg, null, null, GLASS_FONT_SIZE, true,
                        (int) ((double) getSize().height * 0.25));
            }
        }
    };
    worker.execute();

}

From source file:de.cismet.cids.custom.objecteditors.utils.VermessungUmleitungPanel.java

/**
 * DOCUMENT ME!/*from w  w w  .j a  v  a  2s .  com*/
 */
private void createLinkFile() {
    final SwingWorker<Boolean, Void> worker = new SwingWorker<Boolean, Void>() {

        @Override
        protected Boolean doInBackground() throws Exception {
            if (initError) {
                return false;
            }
            final String filename = createFilename();
            final File f = File.createTempFile(filename, ".txt");
            final FileWriter fw = new FileWriter(f);
            final BufferedWriter bfw = new BufferedWriter(fw);
            bfw.write(getLinkDocument(), 0, getLinkDocument().length());
            bfw.flush();
            bfw.close();
            webDavHelper.uploadFileToWebDAV(filename + ".txt", f, createDirName(), editor,
                    getConnectionContext());
            return true;
        }

        @Override
        protected void done() {
            try {
                if (!get()) {
                    final org.jdesktop.swingx.error.ErrorInfo ei = new ErrorInfo(
                            org.openide.util.NbBundle.getMessage(VermessungUmleitungPanel.class,
                                    "VermessungUmleitungPanel.errorDialog.title"),
                            org.openide.util.NbBundle.getMessage(VermessungUmleitungPanel.class,
                                    "VermessungUmleitungPanel.errorDialog.create.message"),
                            null, null, null, Level.ALL, null);
                    JXErrorPane.showDialog(
                            StaticSwingTools.getParentFrameIfNotNull(VermessungUmleitungPanel.this), ei);
                    showError();
                    return;
                }
                editor.handleUmleitungCreated(lastCheckedURL);
            } catch (InterruptedException ex) {
                LOG.error("Create Link File Worker was interrupted.", ex);
            } catch (Exception ex) {
                LOG.error("Error in Create Link File worker", ex);
                final org.jdesktop.swingx.error.ErrorInfo ei = new ErrorInfo(
                        org.openide.util.NbBundle.getMessage(VermessungUmleitungPanel.class,
                                "VermessungUmleitungPanel.errorDialog.title"),
                        org.openide.util.NbBundle.getMessage(VermessungUmleitungPanel.class,
                                "VermessungUmleitungPanel.errorDialog.create.message"),
                        ex.getMessage(), null, ex, Level.ALL, null);
                JXErrorPane.showDialog(StaticSwingTools.getParentFrameIfNotNull(VermessungUmleitungPanel.this),
                        ei);
            }
        }
    };
    worker.execute();
}

From source file:org.eumetsat.metop.visat.SounderInfoView.java

private void updateAngularRelationFields(final Ifov selectedIfov, final EpsFile epsFile) {
    final SwingWorker<AngularRelation, Object> worker = new SwingWorker<AngularRelation, Object>() {
        @Override/*ww  w.j av a2  s  .  c  o  m*/
        protected AngularRelation doInBackground() throws Exception {
            return readAngularRelation(epsFile, selectedIfov);
        }

        @Override
        protected void done() {
            try {
                final AngularRelation angularRelation = get();
                vzaTextField.setText(Double.toString(angularRelation.vza));
                vaaTextField.setText(Double.toString(angularRelation.vaa));
                szaTextField.setText(Double.toString(angularRelation.sza));
                saaTextField.setText(Double.toString(angularRelation.saa));
            } catch (InterruptedException e) {
                clearAngularRelationFields(IO_ERROR);
            } catch (ExecutionException e) {
                clearAngularRelationFields(IO_ERROR);
            }
        }
    };
    worker.execute();
}