Example usage for javax.swing SwingWorker cancel

List of usage examples for javax.swing SwingWorker cancel

Introduction

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

Prototype

public final boolean cancel(boolean mayInterruptIfRunning) 

Source Link

Usage

From source file:com.mirth.connect.connectors.jdbc.DatabaseMetadataDialog.java

private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_cancelButtonActionPerformed
    if (metaDataWorkerId != null) {
        SwingWorker<Object, Void> worker = parentConnector.getWorker(metaDataWorkerId);
        if (worker != null) {
            worker.cancel(true);
        }/*from   w ww . j  a v a2 s  . co m*/
    }
    this.dispose();
}

From source file:com.mirth.connect.connectors.jdbc.DatabaseMetadataDialog.java

/**
 * Action to send request to server and attempt to retrieve the tables based on the filter
 * criteria./*from w ww  .  ja v  a  2 s.co  m*/
 * 
 * @param evt
 *            Action event triggered
 */
private void filterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_filterButtonActionPerformed
    // retrieve the table pattern filter
    databaseConnectionInfo.setTableNamePatternExpression(filterTableTextField.getText());

    // Cancel any previous workers that had been called.
    if (metaDataWorkerId != null) {
        SwingWorker<Object, Void> worker = parentConnector.getWorker(metaDataWorkerId);
        if (worker != null) {
            worker.cancel(true);
        }
        metaDataWorkerId = null;
    }

    ResponseHandler handler = new ResponseHandler() {
        @Override
        public void handle(Object response) {
            Set<Table> metaData = (Set<Table>) response;
            if (metaData == null) {
                parent.alertError(parent,
                        "Could not retrieve database metadata.  Please ensure that your driver, URL, username, and password are correct.");
            } else {
                // format table information into presentation
                makeIncludedMetaDataTable(metaData);
            }
            metaDataWorkerId = null;
        }
    };

    Set<String> tableNamePatterns = new HashSet<String>(
            Arrays.asList(databaseConnectionInfo.getTableNamePatternExpression().trim().split("[, ]+")));
    try {
        metaDataWorkerId = UUID.randomUUID().toString();
        parentConnector.getServlet(DatabaseConnectorServletInterface.class, "Retrieving tables...",
                "Could not retrieve database metadata.  Please ensure that your driver, URL, username, and password are correct.\n\n",
                handler, metaDataWorkerId).getTables(parent.channelEditPanel.currentChannel.getId(),
                        parent.channelEditPanel.currentChannel.getName(), databaseConnectionInfo.getDriver(),
                        databaseConnectionInfo.getUrl(), databaseConnectionInfo.getUsername(),
                        databaseConnectionInfo.getPassword(), tableNamePatterns,
                        databaseConnectionInfo.getSelectLimit(), databaseConnectionInfo.getResourceIds());
    } catch (ClientException e) {
        // Should not happen
    }
}

From source file:de.tntinteractive.portalsammler.gui.MainDialog.java

private void poll(final Gui gui) {

    this.pollButton.setEnabled(false);

    final Settings settings = this.getStore().getSettings().deepClone();
    final ProgressMonitor progress = new ProgressMonitor(this, "Sammle Daten aus den Quell-Portalen...", "...",
            0, settings.getSize());/*from  w  ww  .  j  a v a 2  s.co m*/
    progress.setMillisToDecideToPopup(0);
    progress.setMillisToPopup(0);
    progress.setProgress(0);

    final SwingWorker<String, String> task = new SwingWorker<String, String>() {

        @Override
        protected String doInBackground() throws Exception {
            final StringBuilder summary = new StringBuilder();
            int cnt = 0;
            for (final String id : settings.getAllSettingIds()) {
                if (this.isCancelled()) {
                    break;
                }
                cnt++;
                this.publish(cnt + ": " + id);
                final Pair<Integer, Integer> counts = MainDialog.this.pollSingleSource(settings, id);
                summary.append(id).append(": ");
                if (counts != null) {
                    summary.append(counts.getLeft()).append(" neu, ").append(counts.getRight())
                            .append(" schon bekannt\n");
                } else {
                    summary.append("Fehler!\n");
                }
                this.setProgress(cnt);
            }
            MainDialog.this.getStore().writeMetadata();
            return summary.toString();
        }

        @Override
        protected void process(final List<String> ids) {
            progress.setNote(ids.get(ids.size() - 1));
        }

        @Override
        public void done() {
            MainDialog.this.pollButton.setEnabled(true);
            MainDialog.this.table.refreshContents();
            try {
                final String summary = this.get();
                JOptionPane.showMessageDialog(MainDialog.this, summary, "Abruf-Zusammenfassung",
                        JOptionPane.INFORMATION_MESSAGE);
            } catch (final Exception e) {
                gui.showError(e);
            }
        }

    };

    task.addPropertyChangeListener(new PropertyChangeListener() {
        @Override
        public void propertyChange(final PropertyChangeEvent evt) {
            if ("progress".equals(evt.getPropertyName())) {
                progress.setProgress((Integer) evt.getNewValue());
            }
            if (progress.isCanceled()) {
                task.cancel(true);
            }
        }
    });

    task.execute();
}

From source file:org.usfirst.frc.team2084.neuralnetwork.HeadingNeuralNetworkTrainer.java

private void trainNetwork() {
    if (!training) {

        // Set training flag and disable button
        training = true;/*from  w w w  . j a  v  a2 s . c o  m*/
        trainButton.setEnabled(false);

        final ProgressMonitor progressMonitor = new ProgressMonitor(frame, "Training Network...", "", 0, 100);
        progressMonitor.setMillisToDecideToPopup(100);
        progressMonitor.setMillisToPopup(400);

        @SuppressWarnings("unchecked")
        final ArrayList<XYDataItem> data = new ArrayList<>(outputGraphDataSeries.getItems());

        final int maxProgress = iterations * data.size();

        final SwingWorker<Void, Void> trainingWorker = new SwingWorker<Void, Void>() {

            @Override
            protected Void doInBackground() throws Exception {
                // Reset the neural network to default values
                synchronized (this) {
                    network.reset();
                    network.setEta(eta);
                    network.setMomentum(momentum);
                }

                outer: for (int j = 0; j < iterations; j++) {
                    for (int i = 0; i < data.size(); i++) {
                        if (!isCancelled()) {
                            XYDataItem d = data.get(i);
                            double error = convertAngleToInput(d.getXValue());
                            double output = d.getYValue();
                            synchronized (this) {
                                network.feedForward(error);
                                network.backPropagation(output);
                            }
                            int jl = j;
                            int il = i;
                            int progress = (int) (((float) (data.size() * jl + il + 1) / maxProgress) * 100);
                            setProgress(progress);
                        } else {
                            break outer;
                        }
                    }
                }

                displayNetwork();
                return null;
            }

            @Override
            protected void done() {
                training = false;
                trainButton.setEnabled(true);
                progressMonitor.close();
            }
        };
        trainingWorker.addPropertyChangeListener(new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if (evt.getPropertyName().equals("progress")) {
                    progressMonitor.setProgress((int) evt.getNewValue());
                }
                if (progressMonitor.isCanceled()) {
                    trainingWorker.cancel(true);
                }
            }
        });
        trainingWorker.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();//  w ww . j  a  v a 2 s.co 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;
}

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

protected boolean LoadDXF(String filename) {
    if (ChooseImageConversionOptions(true) == false)
        return false;

    // where to save temp output file?
    final String destinationFile = GetTempDestinationFile();
    final String srcFile = filename;

    TabToLog();/*from   ww w .  j  a v  a2  s  . co  m*/

    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>() {
        public boolean ok = false;

        @SuppressWarnings("unchecked")
        @Override
        public Void doInBackground() {
            Log("<font color='green'>" + translator.get("Converting") + " " + destinationFile + "</font>\n");

            Parser parser = ParserBuilder.createDefaultParser();

            double dxf_x2 = 0;
            double dxf_y2 = 0;
            OutputStreamWriter out = null;

            try {
                out = new OutputStreamWriter(new FileOutputStream(destinationFile), "UTF-8");
                DrawingTool tool = machineConfiguration.GetCurrentTool();
                out.write(machineConfiguration.GetConfigLine() + ";\n");
                out.write(machineConfiguration.GetBobbinLine() + ";\n");
                out.write("G00 G90;\n");
                tool.WriteChangeTo(out);
                tool.WriteOff(out);

                parser.parse(srcFile, DXFParser.DEFAULT_ENCODING);
                DXFDocument doc = parser.getDocument();
                Bounds b = doc.getBounds();
                double width = b.getMaximumX() - b.getMinimumX();
                double height = b.getMaximumY() - b.getMinimumY();
                double cx = (b.getMaximumX() + b.getMinimumX()) / 2.0f;
                double cy = (b.getMaximumY() + b.getMinimumY()) / 2.0f;
                double sy = machineConfiguration.GetPaperHeight() * 10 / height;
                double sx = machineConfiguration.GetPaperWidth() * 10 / width;
                double scale = (sx < sy ? sx : sy) * machineConfiguration.paper_margin;
                sx = scale * (machineConfiguration.reverseForGlass ? -1 : 1);
                // count all entities in all layers
                Iterator<DXFLayer> layer_iter = (Iterator<DXFLayer>) doc.getDXFLayerIterator();
                int entity_total = 0;
                int entity_count = 0;
                while (layer_iter.hasNext()) {
                    DXFLayer layer = (DXFLayer) layer_iter.next();
                    Log("<font color='yellow'>Found layer " + layer.getName() + "</font>\n");
                    Iterator<String> entity_iter = (Iterator<String>) layer.getDXFEntityTypeIterator();
                    while (entity_iter.hasNext()) {
                        String entity_type = (String) entity_iter.next();
                        List<DXFEntity> entity_list = (List<DXFEntity>) layer.getDXFEntities(entity_type);
                        Log("<font color='yellow'>+ Found " + entity_list.size() + " of type " + entity_type
                                + "</font>\n");
                        entity_total += entity_list.size();
                    }
                }
                // set the progress meter
                pm.setMinimum(0);
                pm.setMaximum(entity_total);

                // convert each entity
                layer_iter = doc.getDXFLayerIterator();
                while (layer_iter.hasNext()) {
                    DXFLayer layer = (DXFLayer) layer_iter.next();

                    Iterator<String> entity_type_iter = (Iterator<String>) layer.getDXFEntityTypeIterator();
                    while (entity_type_iter.hasNext()) {
                        String entity_type = (String) entity_type_iter.next();
                        List<DXFEntity> entity_list = layer.getDXFEntities(entity_type);

                        if (entity_type.equals(DXFConstants.ENTITY_TYPE_LINE)) {
                            for (int i = 0; i < entity_list.size(); ++i) {
                                pm.setProgress(entity_count++);
                                DXFLine entity = (DXFLine) entity_list.get(i);
                                Point start = entity.getStartPoint();
                                Point end = entity.getEndPoint();

                                double x = (start.getX() - cx) * sx;
                                double y = (start.getY() - cy) * sy;
                                double x2 = (end.getX() - cx) * sx;
                                double y2 = (end.getY() - cy) * sy;

                                // is it worth drawing this line?
                                double dx = x2 - x;
                                double dy = y2 - y;
                                if (dx * dx + dy * dy < tool.GetDiameter() / 2.0) {
                                    continue;
                                }

                                dx = dxf_x2 - x;
                                dy = dxf_y2 - y;

                                if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) {
                                    if (tool.DrawIsOn()) {
                                        tool.WriteOff(out);
                                    }
                                    tool.WriteMoveTo(out, (float) x, (float) y);
                                }
                                if (tool.DrawIsOff()) {
                                    tool.WriteOn(out);
                                }
                                tool.WriteMoveTo(out, (float) x2, (float) y2);
                                dxf_x2 = x2;
                                dxf_y2 = y2;
                            }
                        } else if (entity_type.equals(DXFConstants.ENTITY_TYPE_SPLINE)) {
                            for (int i = 0; i < entity_list.size(); ++i) {
                                pm.setProgress(entity_count++);
                                DXFSpline entity = (DXFSpline) entity_list.get(i);
                                entity.setLineWeight(30);
                                DXFPolyline polyLine = DXFSplineConverter.toDXFPolyline(entity);
                                boolean first = true;
                                for (int j = 0; j < polyLine.getVertexCount(); ++j) {
                                    DXFVertex v = polyLine.getVertex(j);
                                    double x = (v.getX() - cx) * sx;
                                    double y = (v.getY() - cy) * sy;
                                    double dx = dxf_x2 - x;
                                    double dy = dxf_y2 - y;

                                    if (first == true) {
                                        first = false;
                                        if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) {
                                            // line does not start at last tool location, lift and move.
                                            if (tool.DrawIsOn()) {
                                                tool.WriteOff(out);
                                            }
                                            tool.WriteMoveTo(out, (float) x, (float) y);
                                        }
                                        // else line starts right here, do nothing.
                                    } else {
                                        // not the first point, draw.
                                        if (tool.DrawIsOff())
                                            tool.WriteOn(out);
                                        if (j < polyLine.getVertexCount() - 1
                                                && dx * dx + dy * dy < tool.GetDiameter() / 2.0)
                                            continue; // less than 1mm movement?  Skip it. 
                                        tool.WriteMoveTo(out, (float) x, (float) y);
                                    }
                                    dxf_x2 = x;
                                    dxf_y2 = y;
                                }
                            }
                        } else if (entity_type.equals(DXFConstants.ENTITY_TYPE_POLYLINE)) {
                            for (int i = 0; i < entity_list.size(); ++i) {
                                pm.setProgress(entity_count++);
                                DXFPolyline entity = (DXFPolyline) entity_list.get(i);
                                boolean first = true;
                                for (int j = 0; j < entity.getVertexCount(); ++j) {
                                    DXFVertex v = entity.getVertex(j);
                                    double x = (v.getX() - cx) * sx;
                                    double y = (v.getY() - cy) * sy;
                                    double dx = dxf_x2 - x;
                                    double dy = dxf_y2 - y;

                                    if (first == true) {
                                        first = false;
                                        if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) {
                                            // line does not start at last tool location, lift and move.
                                            if (tool.DrawIsOn()) {
                                                tool.WriteOff(out);
                                            }
                                            tool.WriteMoveTo(out, (float) x, (float) y);
                                        }
                                        // else line starts right here, do nothing.
                                    } else {
                                        // not the first point, draw.
                                        if (tool.DrawIsOff())
                                            tool.WriteOn(out);
                                        if (j < entity.getVertexCount() - 1
                                                && dx * dx + dy * dy < tool.GetDiameter() / 2.0)
                                            continue; // less than 1mm movement?  Skip it. 
                                        tool.WriteMoveTo(out, (float) x, (float) y);
                                    }
                                    dxf_x2 = x;
                                    dxf_y2 = y;
                                }
                            }
                        }
                    }
                }

                // entities finished.  Close up file.
                tool.WriteOff(out);
                tool.WriteMoveTo(out, 0, 0);

                ok = true;
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                try {
                    if (out != null)
                        out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            pm.setProgress(100);
            return null;
        }

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

    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;
}

From source file:org.ut.biolab.medsavant.client.region.RegionWizard.java

private AbstractWizardPage getGenesPage() {
    return new DefaultWizardPage(PAGENAME_GENES) {
        private static final int GENE_SELECTION_PANE_WIDTH = 350;
        private JPanel leftSide;
        private GeneSelectionPanel geneManiaResultsPanel;
        private Set<String> geneManiaGeneNames = null;

        {/* w  w w  .  ja v a2 s.c  o m*/
            selectedGenesPanel = new GeneSelectionPanel(true, true);
            sourceGenesPanel = new GeneSelectionPanel(true, true);
            geneManiaResultsPanel = new GeneSelectionPanel(true, true) {
                @Override
                protected void dragAndDropAddGenes(Set<Gene> geneSet) {
                    Set<Object> genesToMoveToGeneManiaPanel = new HashSet<Object>(geneManiaGeneNames);
                    genesToMoveToGeneManiaPanel.retainAll(selectedGenesPanel.getSelectedKeys());
                    selectedGenesPanel.copyItems(geneManiaResultsPanel, genesToMoveToGeneManiaPanel);
                    selectedGenesPanel.moveSelectedItems(sourceGenesPanel);
                }

                @Override
                protected void dragAndDropRemoveKeys(Set<Object> keySet) {
                    Set<Object> keys = geneManiaResultsPanel.getSelectedKeys();
                    geneManiaResultsPanel.removeRows(keys);
                    sourceGenesPanel.removeRows(keys);
                }
            };
            geneManiaResultsPanel.setOddRowColor(new Color(242, 249, 245));

            runGeneManiaButton = new JButton("Run GeneMANIA");
            runGeneManiaButton.setEnabled(!DirectorySettings.isGeneManiaInstalled());

            ListSelectionListener selectionListener = new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent lse) {
                    int numSel = sourceGenesPanel.getNumSelected() + selectedGenesPanel.getNumSelected();
                    if (geneManiaGeneNames != null) {
                        numSel += geneManiaResultsPanel.getNumSelected();
                    }
                    if (GenemaniaInfoRetriever.isGeneManiaDownloading()) {
                        runGeneManiaButton.setEnabled(false);
                    } else {
                        runGeneManiaButton.setEnabled(numSel > 0 || !DirectorySettings.isGeneManiaInstalled());
                    }
                }
            };

            sourceGenesPanel.getTable().getSelectionModel().addListSelectionListener(selectionListener);
            selectedGenesPanel.getTable().getSelectionModel().addListSelectionListener(selectionListener);
            selectedGenesPanel.getTable().getModel().addTableModelListener(new TableModelListener() {
                @Override
                public void tableChanged(TableModelEvent tme) {
                    if (selectedGenesPanel.getData().length > 0) {
                        fireButtonEvent(ButtonEvent.ENABLE_BUTTON, ButtonNames.NEXT);
                    } else {
                        fireButtonEvent(ButtonEvent.DISABLE_BUTTON, ButtonNames.NEXT);
                    }
                }
            });

            selectedGenesPanel.setPreferredSize(
                    new Dimension(GENE_SELECTION_PANE_WIDTH, selectedGenesPanel.getPreferredSize().height));

            final JPanel outerLeftSide = new JPanel();
            outerLeftSide.setLayout(new BoxLayout(outerLeftSide, BoxLayout.X_AXIS));

            leftSide = new JPanel();
            leftSide.setLayout(new BoxLayout(leftSide, BoxLayout.Y_AXIS));
            leftSide.add(sourceGenesPanel);
            outerLeftSide.add(leftSide);
            final JPanel bg = new JPanel();
            bg.setLayout(new BoxLayout(bg, BoxLayout.Y_AXIS));

            JButton addButton = new JButton("Add ");
            JButton removeButton = new JButton("? Remove");

            sourceGenesPanel.getTable().addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent me) {
                    if (me.getClickCount() == 2) {
                        sourceGenesPanel.moveSelectedItems(selectedGenesPanel);
                    }
                }
            });

            selectedGenesPanel.getTable().addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent me) {
                    if (me.getClickCount() == 2) {
                        if (geneManiaGeneNames != null) {
                            Set<Object> genesToMoveToGeneManiaPanel = new HashSet<Object>(geneManiaGeneNames);
                            genesToMoveToGeneManiaPanel.retainAll(selectedGenesPanel.getSelectedKeys());
                            selectedGenesPanel.copyItems(geneManiaResultsPanel, genesToMoveToGeneManiaPanel);
                        }
                        selectedGenesPanel.moveSelectedItems(sourceGenesPanel);
                    }
                }
            });

            geneManiaResultsPanel.getTable().addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent me) {
                    if (me.getClickCount() == 2) {
                        Set<Object> keys = geneManiaResultsPanel.getSelectedKeys();
                        geneManiaResultsPanel.moveSelectedItems(selectedGenesPanel);
                        sourceGenesPanel.moveItems(selectedGenesPanel, keys);
                    }
                }
            });

            addButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ae) {
                    if (geneManiaGeneNames != null) {
                        Set<Object> keys = geneManiaResultsPanel.getSelectedKeys();
                        geneManiaResultsPanel.moveSelectedItems(selectedGenesPanel);
                        sourceGenesPanel.moveItems(selectedGenesPanel, keys);
                    } else {
                        sourceGenesPanel.moveSelectedItems(selectedGenesPanel);
                    }
                }
            });

            removeButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ae) {
                    if (geneManiaGeneNames != null) {
                        Set<Object> genesToMoveToGeneManiaPanel = new HashSet<Object>(geneManiaGeneNames);
                        genesToMoveToGeneManiaPanel.retainAll(selectedGenesPanel.getSelectedKeys());
                        selectedGenesPanel.copyItems(geneManiaResultsPanel, genesToMoveToGeneManiaPanel);
                    }
                    selectedGenesPanel.moveSelectedItems(sourceGenesPanel);
                }
            });

            bg.add(Box.createVerticalGlue());
            bg.add(addButton);
            bg.add(removeButton);
            bg.add(Box.createVerticalGlue());
            outerLeftSide.add(bg);

            JPanel rightSide = new JPanel();
            rightSide.setLayout(new BoxLayout(rightSide, BoxLayout.Y_AXIS));
            rightSide.add(selectedGenesPanel);
            rightSide.add(runGeneManiaButton);

            final JSplitPane hsplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, outerLeftSide, rightSide);
            hsplitPane.setResizeWeight(1);
            addComponent(hsplitPane, true);

            if (!DirectorySettings.isGeneManiaInstalled()) {
                runGeneManiaButton.setText("Download GeneMANIA");
                if (GenemaniaInfoRetriever.isGeneManiaDownloading()) {
                    runGeneManiaButton.setEnabled(false);
                    registerDownloadListener();
                }
            }

            runGeneManiaButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ae) {

                    if (!DirectorySettings.isGeneManiaInstalled()) {
                        int response = DialogUtils.askYesNo("Download GeneMANIA?",
                                "GeneMANIA is not yet installed.  Do you want to download and install it now?");
                        try {
                            if (response == DialogUtils.OK) {
                                runGeneManiaButton.setText("Run GeneMANIA");
                                runGeneManiaButton.setEnabled(false);
                                registerDownloadListener();

                                /*
                                 DownloadTask dt = GenemaniaInfoRetriever.getGeneManiaDownloadTask();
                                 dt.addPropertyChangeListener(new PropertyChangeListener() {
                                 @Override
                                 public void propertyChange(PropertyChangeEvent evt) {
                                 if (evt.getPropertyName().equals("downloadState")) {
                                 DownloadTask.DownloadState ds = (DownloadTask.DownloadState) evt.getNewValue();
                                 if (ds == DownloadTask.DownloadState.CANCELLED
                                 || ds == DownloadTask.DownloadState.FINISHED) {
                                        
                                 runGeneManiaButton.setEnabled(
                                 (selectedGenesPanel.getNumSelected() + sourceGenesPanel.getNumSelected()) > 0);
                                 }
                                 }
                                 }
                                 });
                                 */
                                GenemaniaInfoRetriever.getGeneManiaDownloadTask().execute();
                            }
                        } catch (IOException e) {
                            DialogUtils.displayMessage("Error downloading GeneMANIA files");
                            LOG.error(e);
                        }
                    } else {

                        final List<String> selectedGenes = new LinkedList<String>();
                        for (Gene g : selectedGenesPanel.getSelectedGenes()) {
                            selectedGenes.add(g.getName());
                        }
                        for (Gene g : sourceGenesPanel.getSelectedGenes()) {
                            selectedGenes.add(g.getName());
                        }
                        if (geneManiaGeneNames != null) {
                            for (Gene g : geneManiaResultsPanel.getSelectedGenes()) {
                                selectedGenes.add(g.getName());
                            }
                        }
                        final JButton closeGeneManiaButton = new JButton("? Close GeneMANIA results");
                        closeGeneManiaButton.setEnabled(false);
                        final JPanel geneManiaContainingPanel = new JPanel();
                        geneManiaContainingPanel
                                .setLayout(new BoxLayout(geneManiaContainingPanel, BoxLayout.Y_AXIS));

                        final SwingWorker geneManiaWorker = new SwingWorker() {
                            private List<Object[]> results;

                            @Override
                            public void done() {
                                Object[][] newdata = new Object[results.size()][4];
                                results.toArray(newdata);
                                geneManiaResultsPanel.updateData(newdata);
                                geneManiaResultsPanel.updateView();
                                geneManiaContainingPanel.removeAll();
                                geneManiaContainingPanel.add(geneManiaResultsPanel);
                                geneManiaContainingPanel.revalidate();
                                geneManiaContainingPanel.repaint();
                                closeGeneManiaButton.setEnabled(true);
                            }

                            @Override
                            public Object doInBackground() {
                                try {
                                    GenemaniaInfoRetriever genemania = new GenemaniaInfoRetriever();
                                    genemania.setGenes(selectedGenes);
                                    List<String> geneNameList = genemania.getRelatedGeneNamesByScore();
                                    geneManiaGeneNames = new HashSet<String>();
                                    geneManiaGeneNames.addAll(geneNameList);
                                    LOG.debug("Found " + geneNameList.size() + " related genes");

                                    results = new ArrayList<Object[]>(geneNameList.size());

                                    int i = 0;
                                    for (String gene : geneNameList) {
                                        if (isCancelled()) {
                                            return null;
                                        }
                                        Gene g = GeneSetFetcher.getInstance().getGeneDictionary().get(gene);
                                        if (g == null) {
                                            LOG.warn("No gene found for " + gene);
                                        } else if (!selectedGenesPanel.hasKey(g.getName())) {
                                            results.add(new Object[] { g.getName(), g.getChrom(), g.getStart(),
                                                    g.getEnd() });
                                        }
                                    }
                                } catch (IOException e) {
                                    LOG.error(e);
                                } catch (ApplicationException e) {
                                    LOG.error(e);
                                } catch (DataStoreException e) {
                                    LOG.error(e);
                                } catch (NoRelatedGenesInfoException e) {
                                    LOG.error(e);
                                }
                                return null;
                            }
                        };

                        leftSide.removeAll();

                        closeGeneManiaButton.addActionListener(new ActionListener() {
                            @Override
                            public void actionPerformed(ActionEvent ae) {
                                try {
                                    geneManiaWorker.cancel(true);
                                } catch (Exception e) {
                                    //genemania throws exceptions when cancelled
                                }
                                leftSide.removeAll();
                                leftSide.add(sourceGenesPanel);
                                leftSide.validate();
                                leftSide.repaint();
                                geneManiaGeneNames = null;
                            }
                        });

                        JPanel closeButtonPanel = new JPanel();
                        closeButtonPanel.setLayout(new BoxLayout(closeButtonPanel, BoxLayout.X_AXIS));
                        closeButtonPanel.add(closeGeneManiaButton);
                        closeButtonPanel.add(Box.createHorizontalGlue());

                        leftSide.add(closeButtonPanel);

                        geneManiaContainingPanel.add(new WaitPanel("Querying GeneMANIA for related genes"));

                        leftSide.add(geneManiaContainingPanel);
                        leftSide.validate();
                        leftSide.repaint();
                        geneManiaWorker.execute();

                    } //end else
                }//end actionPerformed
            });//end ActionListener
        }

        @Override
        public void setupWizardButtons() {
            fireButtonEvent(ButtonEvent.HIDE_BUTTON, ButtonNames.FINISH);
            fireButtonEvent(ButtonEvent.SHOW_BUTTON, ButtonNames.BACK);

            if (selectedGenesPanel.getNumSelected() > 0) {
                fireButtonEvent(ButtonEvent.ENABLE_BUTTON, ButtonNames.NEXT);
            } else {
                fireButtonEvent(ButtonEvent.DISABLE_BUTTON, ButtonNames.NEXT);
            }
        }
    };
}