Example usage for javax.swing SwingWorker execute

List of usage examples for javax.swing SwingWorker execute

Introduction

In this page you can find the example usage for javax.swing SwingWorker execute.

Prototype

public final void execute() 

Source Link

Document

Schedules this SwingWorker for execution on a worker thread.

Usage

From source file:net.sourceforge.atunes.kernel.modules.search.SearchHandler.java

/**
 * Generic method to update any searchable object.
 * /*  www  . j av a 2  s  .  c  om*/
 * @param searchableObject
 *            the searchable object
 */

private void updateSearchIndex(final SearchableObject searchableObject) {
    SwingWorker<Void, Void> refreshSearchIndex = new SwingWorker<Void, Void>() {
        private IndexWriter indexWriter;

        @Override
        protected Void doInBackground() {
            ReadWriteLock searchIndexLock = indexLocks.get(searchableObject);
            try {
                searchIndexLock.writeLock().lock();
                initSearchIndex();
                updateSearchIndex(searchableObject.getElementsToIndex());
                finishSearchIndex();
                return null;
            } finally {
                searchIndexLock.writeLock().unlock();
                currentIndexingWorks.put(searchableObject, Boolean.FALSE);
            }
        }

        @Override
        protected void done() {
            // Nothing to do
        }

        private void initSearchIndex() {
            getLogger().info(LogCategories.HANDLER, "Updating index for " + searchableObject.getClass());
            try {
                FileUtils.deleteDirectory(new File(searchableObject.getPathToIndex()));
                indexWriter = new IndexWriter(searchableObject.getPathToIndex(), new SimpleAnalyzer(),
                        IndexWriter.MaxFieldLength.UNLIMITED);
            } catch (CorruptIndexException e) {
                getLogger().error(LogCategories.HANDLER, e);
            } catch (LockObtainFailedException e) {
                getLogger().error(LogCategories.HANDLER, e);
            } catch (IOException e) {
                getLogger().error(LogCategories.HANDLER, e);
            }
        }

        private void updateSearchIndex(List<AudioObject> audioObjects) {
            getLogger().info(LogCategories.HANDLER, "update search index");
            if (indexWriter != null) {
                for (AudioObject audioObject : audioObjects) {
                    Document d = searchableObject.getDocumentForElement(audioObject);
                    // Add dummy field
                    d.add(new Field(INDEX_FIELD_DUMMY, INDEX_FIELD_DUMMY, Field.Store.YES,
                            Field.Index.NOT_ANALYZED_NO_NORMS));

                    try {
                        indexWriter.addDocument(d);
                    } catch (CorruptIndexException e) {
                        getLogger().error(LogCategories.HANDLER, e);
                    } catch (IOException e) {
                        getLogger().error(LogCategories.HANDLER, e);
                    }
                }
            }
        }

        private void finishSearchIndex() {
            getLogger().info(LogCategories.HANDLER,
                    StringUtils.getString("Update index for ", searchableObject.getClass(), " finished"));
            if (indexWriter != null) {
                try {
                    indexWriter.optimize();
                    indexWriter.close();

                    indexWriter = null;
                } catch (CorruptIndexException e) {
                    getLogger().error(LogCategories.HANDLER, e);
                } catch (IOException e) {
                    getLogger().error(LogCategories.HANDLER, e);
                }
            }
        }

    };
    if (currentIndexingWorks.get(searchableObject) == null || !currentIndexingWorks.get(searchableObject)) {
        currentIndexingWorks.put(searchableObject, Boolean.TRUE);
        refreshSearchIndex.execute();
    }

}

From source file:display.containers.FileManager.java

/** Add the files that are contained within the directory of this node.
Thanks to Hovercraft Full Of Eels. */
private void showChildren(final Path node) {
    //tree.setEnabled(false);

    SwingWorker<Void, File> worker = new SwingWorker<Void, File>() {
        @Override//from w  w w  . j a va2  s.  c o  m
        public Void doInBackground() {
            table.setEnabled(false);
            File file = (File) node.toFile();
            setCurrentDir(file);
            if (file.isDirectory()) {
                File[] files = fileSystemView.getFiles(file, !UserProfile.SHOW_HIDDEN_FILES); //!!
                File[] filesTemp = new File[files.length + 1];
                File[] filesWithParent;
                filesTemp[0] = new File(file.getAbsolutePath() + "/..");
                for (int i = 1; i < filesTemp.length; i++) {
                    filesTemp[i] = files[i - 1];
                }
                switch (getMode()) {
                case 1:
                    List<File> list = new ArrayList<File>();
                    if (file.toPath().equals(SystemSettings.SERVER_INFO.getServerDir())) {
                        for (File fi : filesTemp) {
                            for (Project p : UserProfile.CURRENT_USER.getProjects()) {
                                if ((ServerInfo.WORKSPACE_PREFIXE + p.getNom()).equals(fi.getName())) {
                                    list.add(fi);
                                }
                            }
                        }
                        filesWithParent = list.toArray(new File[list.size()]);
                    } else {
                        filesWithParent = filesTemp;
                    }

                    break;
                case 2:
                    List<File> list2 = new ArrayList<File>();
                    if (file.toPath().equals(SystemSettings.SERVER_INFO.getServerDir())) {
                        for (File fi : filesTemp) {
                            if (fi.getName().equals(ServerInfo.NRI_DICOM_NAME)
                                    || fi.getName().equals(ServerInfo.NRI_ANALYSE_NAME)) {
                                list2.add(fi);
                            }
                        }
                        filesWithParent = list2.toArray(new File[list2.size()]);
                    } else {
                        filesWithParent = filesTemp;
                    }
                    break;
                default:
                    filesWithParent = filesTemp;
                }
                if (filesWithParent != null) {
                    setTableData(filesWithParent);
                }
            }
            return null;
        }
    };
    worker.execute();
}

From source file:au.org.ala.delta.intkey.model.IntkeyContext.java

/**
 * Read and execute the specified dataset startup file. This file may be
 * either a "webstart" file, or a file containing actual directives to
 * initialize the dataset./* w ww  . j  a va2s .  c  o m*/
 * 
 * This method will block while the calling thread while the file is read,
 * the dataset is loaded, and other directives in the file are executed.
 * 
 * @param datasetFileURL
 *            The dataset initialization file
 * @return SwingWorker used to load the dataset in a separate thread - unit
 *         tests need this so that they can block until the dataset is
 *         loaded.
 */
public synchronized void newDataSetFile(final URL datasetFileURL) {
    Logger.log("Reading in directives from url: %s", datasetFileURL.toString());

    // Close any dialogs that have been left open.
    IntKeyDialogController.closeWindows();

    cleanupOldDataset();

    initializeIdentification();

    // Loading of a new dataset can take a long time and hence can lock up
    // the UI. If this method is called from the Swing Event Dispatch
    // Thread, load the
    // new dataset on a background thread using a SwingWorker.
    if (SwingUtilities.isEventDispatchThread()) {
        _appUI.displayBusyMessage(UIUtils.getResourceString("LoadingDataset.caption"));
        SwingWorker<Void, Void> startupWorker = new SwingWorker<Void, Void>() {

            @Override
            protected Void doInBackground() throws Exception {
                processStartupFile(datasetFileURL);
                return null;
            }

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

                    if (_dataset.getHeading() != null) {
                        appendToLog(_dataset.getHeadingWithoutFormatting());
                    }

                    if (_dataset.getSubHeading() != null) {
                        appendToLog(_dataset.getSubheadingWithoutFormatting());
                    }

                    _appUI.handleNewDataset(_dataset);
                } catch (Exception ex) {
                    Logger.error("Error reading dataset file", ex);
                    _appUI.displayErrorMessage(UIUtils.getResourceString("ErrorReadingReadsetFile.error",
                            datasetFileURL.toString(), ex.getMessage()));
                } finally {
                    _appUI.removeBusyMessage();
                }
            }
        };

        startupWorker.execute();
    } else {
        try {
            processStartupFile(datasetFileURL);

            if (_dataset.getHeading() != null) {
                appendToLog(_dataset.getHeadingWithoutFormatting());
            }

            if (_dataset.getSubHeading() != null) {
                appendToLog(_dataset.getSubheadingWithoutFormatting());
            }

            _appUI.handleNewDataset(_dataset);
        } catch (Exception ex) {
            Logger.error("Error reading dataset file", ex);
            _appUI.displayErrorMessage(UIUtils.getResourceString("ErrorReadingReadsetFile.error",
                    datasetFileURL.toString(), ex.getMessage()));
        }
    }
}

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}.
 * /*w ww.  java 2s .  c  o  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:edu.ku.brc.specify.config.FixAttachments.java

/**
 * @param resultsHashMap/*  w  w w. j a  v a2s . c o m*/
 * @param tableHash
 * @param totalFiles
 */
private void reattachFiles(final HashMap<Integer, Vector<Object[]>> resultsHashMap,
        final HashMap<Integer, AttchTableModel> tableHash, final int totalFiles) {
    final String CNT = "CNT";
    final SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() {
        int filesCnt = 0;

        @Override
        protected Integer doInBackground() throws Exception {
            DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession();
            if (session != null) {
                try {
                    for (int tblId : resultsHashMap.keySet()) {
                        AttchTableModel model = tableHash.get(tblId);
                        int cnt = 0;
                        for (int r = 0; r < model.getRowCount(); r++) {
                            if (model.isRecoverable(r)) {
                                Thread.sleep(100);

                                session.beginTransaction();
                                Integer attachID = model.getAttachmentId(r);
                                Attachment attachment = session.get(Attachment.class, attachID);
                                AttachmentUtils.getAttachmentManager()
                                        .setStorageLocationIntoAttachment(attachment, false);
                                try {
                                    attachment.storeFile(true); // false means do not display an error dialog
                                    session.saveOrUpdate(attachment);
                                    session.commit();
                                    model.setRecovered(r, true);
                                    filesCnt++;

                                } catch (IOException ex) {
                                    session.rollback();
                                }
                            }
                            cnt++;
                            firePropertyChange(CNT, 0, (int) ((double) cnt / (double) totalFiles * 100.0));
                        }
                    }
                } catch (Exception ex) {
                    session.rollback();

                } finally {
                    session.close();
                }
            }
            return null;
        }

        @Override
        protected void done() {
            UIRegistry.clearSimpleGlassPaneMsg();
            UIRegistry.displayInfoMsgDlg(String.format("Files recovered: %d / %d", filesCnt, totalFiles));

            File file = produceSummaryReport(resultsHashMap, tableHash, totalFiles);
            if (file != null) {
                try {
                    AttachmentUtils.openFile(file);
                } catch (Exception e) {
                }
            }

            if (getNumberofBadAttachments() == 0) {
                AppPreferences.getGlobalPrefs().putBoolean("CHECK_ATTCH_ERR", true);
            }
            super.done();
        }
    };

    final SimpleGlassPane glassPane = UIRegistry
            .writeSimpleGlassPaneMsg(String.format("Recovering %d files.", totalFiles), 24);
    glassPane.setProgress(0);

    worker.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            if (CNT.equals(evt.getPropertyName())) {
                glassPane.setProgress((Integer) evt.getNewValue());
            }
        }
    });

    worker.execute();
}

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

public void doRedeployAll() {
    if (!parent.alertOption(parent, "Are you sure you want to redeploy all channels?")) {
        return;//from ww  w. jav a2 s .  c  o m
    }

    final String workingId = parent.startWorking("Deploying channels...");
    parent.dashboardPanel.deselectRows(false);
    parent.doShowDashboard();

    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        @Override
        public Void doInBackground() {
            try {
                parent.mirthClient.redeployAllChannels();
            } catch (ClientException e) {
                parent.alertThrowable(parent, e);
            }
            return null;
        }

        @Override
        public void done() {
            parent.stopWorking(workingId);
            parent.doRefreshStatuses(true);
        }
    };

    worker.execute();
}

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

/**
 * //from w  w  w . ja  va 2s.  com
 */
protected void createMasterUser() {
    String saUsrNm = ((JTextField) comps.get("saUserName")).getText();
    if (StringUtils.isNotEmpty(saUsrNm) && saUsrNm.equalsIgnoreCase("root")) {
        UIRegistry.showLocalizedError("MASTER_NO_ROOT");
        ((JTextField) comps.get("saUserName")).setText("");
        return;
    }

    if (!checkPermsForMasterUserCreation()) {
        return;
    }

    if (isOK == null || !isOK) {
        progressBar.setIndeterminate(true);
        progressBar.setVisible(true);

        setUIEnabled(false);

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

        createMUBtn.setVisible(false);

        SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
            @Override
            protected Object doInBackground() throws Exception {
                MasterUserPanel.this.label.setForeground(Color.BLACK);

                isOK = false;
                if (!isEmbedded) {
                    DBMSUserMgr mgr = DBMSUserMgr.getInstance();

                    String dbUserName = properties.getProperty("dbUserName");
                    String dbPassword = properties.getProperty("dbPassword");
                    String dbName = properties.getProperty("dbName");
                    String hostName = properties.getProperty("hostName");

                    String saUserName = ((JTextField) comps.get("saUserName")).getText();
                    String saPassword = ((JTextField) comps.get("saPassword")).getText();

                    if (mgr.connectToDBMS(dbUserName, dbPassword, hostName)) {

                        if (mgr.doesUserExists(saUserName)) {
                            if (!mgr.setPermissions(saUserName, dbName, DBMSUserMgr.PERM_ALL_BASIC)) {
                                errorKey = "ERR_SET_PERM";
                            } else {
                                isOK = true;
                            }
                        }

                        if (!mgr.doesUserExists(saUserName)) {
                            firePropertyChange(propName, 0, 1);

                            isOK = mgr.createUser(saUserName, saPassword, dbName, DBMSUserMgr.PERM_ALL_BASIC);
                            if (!isOK) {
                                errorKey = "ERR_CRE_MASTER";
                            } else {
                                isOK = true;
                            }
                        }
                    } else {
                        errorKey = "NO_CONN_ROOT";
                        isOK = false;
                    }

                    if (mgr != null) {
                        mgr.close();
                    }
                } else {
                    isOK = true;
                }

                return null;
            }

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

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

                setUIEnabled(true);

                updateBtnUI();

                createMUBtn.setVisible(!isOK);

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

                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            nextBtn.doClick();
                        }
                    });

                } else {
                    label.setText(UIRegistry.getResourceString(errorKey));
                    UIRegistry.showLocalizedError(errorKey);
                }
            }
        };

        worker.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(final PropertyChangeEvent evt) {
                if (propName.equals(evt.getPropertyName())) {
                    MasterUserPanel.this.label.setText(UIRegistry.getLocalizedMessage("CREATE_MASTER"));
                }
            }
        });
        worker.execute();
    }
}

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

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

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

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

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

            progressjLabel.setText("");

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

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

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

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

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

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

/**
 * /* www . j  a  v  a  2s. c  o  m*/
 */
private void translateNewItems() {

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

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

    final double total = newKeyList.size();

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

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

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

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

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

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

            UIRegistry.showLocalizedMsg("Done Localizing");

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

        }
    };

    statusBar.setIndeterminate(STATUSBAR_NAME, true);

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

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

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

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

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

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

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

            pm.setProgress(100);
            return null;
        }

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

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

    s.execute();

    return true;
}