Example usage for javax.swing ProgressMonitor isCanceled

List of usage examples for javax.swing ProgressMonitor isCanceled

Introduction

In this page you can find the example usage for javax.swing ProgressMonitor isCanceled.

Prototype

public boolean isCanceled() 

Source Link

Document

Returns true if the user hits the Cancel button or closes the progress dialog.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String message = "Description of Task";
    String note = "subtask";
    String title = "Task Title";
    UIManager.put("ProgressMonitor.progressText", title);

    int min = 0;// www  .j  a  va  2  s .  c o m
    int max = 100;
    JFrame component = new JFrame();
    ProgressMonitor pm = new ProgressMonitor(component, message, note, min, max);

    boolean cancelled = pm.isCanceled();
    if (cancelled) {
        System.out.println("Stop task");
    } else {
        pm.setProgress(100);
        pm.setNote("New Note");
    }
}

From source file:net.ftb.minecraft.MCInstaller.java

public static void setupNewStyle(final String installPath, final ModPack pack, final boolean isLegacy,
        final LoginResponse RESPONSE) {
    List<DownloadInfo> assets = gatherAssets(new File(installPath),
            pack.getMcVersion(Settings.getSettings().getPackVer(pack.getDir())), installPath);
    if (assets != null && assets.size() > 0) {
        Logger.logInfo("Checking/Downloading " + assets.size() + " assets, this may take a while...");

        final ProgressMonitor prog = new ProgressMonitor(LaunchFrame.getInstance(), "Downloading Files...", "",
                0, 100);//from   w  ww . ja v a 2s  . c  om
        prog.setMaximum(assets.size() * 100);

        final AssetDownloader downloader = new AssetDownloader(prog, assets) {
            @Override
            public void done() {
                try {
                    prog.close();
                    if (get()) {
                        Logger.logInfo("Asset downloading complete");
                        launchMinecraft(installPath, pack, RESPONSE, isLegacy);
                    } else {
                        ErrorUtils.tossError("Error occurred during downloading the assets");
                    }
                } catch (CancellationException e) {
                    Logger.logInfo("Asset download interrupted by user");
                } catch (Exception e) {
                    ErrorUtils.tossError("Failed to download files.", e);
                } finally {
                    LaunchFrame.getInstance().getEventBus().post(new EnableObjectsEvent());
                }
            }
        };

        downloader.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if (prog.isCanceled()) {
                    downloader.cancel(false);
                    prog.close();
                } else if (!downloader.isCancelled()) {
                    if ("ready".equals(evt.getPropertyName()))
                        prog.setProgress(downloader.getReady());
                    if ("status".equals(evt.getPropertyName()))
                        prog.setNote(downloader.getStatus());
                }
            }
        });

        downloader.execute();
    } else if (assets == null) {
        LaunchFrame.getInstance().getEventBus().post(new EnableObjectsEvent());
    } else {
        launchMinecraft(installPath, pack, RESPONSE, isLegacy);
    }
}

From source file:com.diversityarrays.update.UpdateDialog.java

private void checkForUpdates(PrintStream ps) {

    StringBuilder sb = new StringBuilder(updateCheckRequest.updateBaseUrl);
    sb.append(updateCheckRequest.versionCode);
    if (RunMode.getRunMode().isDeveloper()) {
        sb.append("-dev"); //$NON-NLS-1$
    }/*  w  ww  . j  a v  a2s. c o m*/
    sb.append(".json"); //$NON-NLS-1$

    final String updateUrl;
    updateUrl = sb.toString();
    // updateUrl = "NONEXISTENT"; // Uncomment to check error

    final ProgressMonitor progressMonitor = new ProgressMonitor(updateCheckRequest.owner,
            Msg.PROGRESS_CHECKING(), null, 0, 0);

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

        @Override
        protected String doInBackground() throws Exception {

            // Thread.sleep(3000); // Uncomment to check delay

            BufferedReader reader = null;
            StringBuffer buffer = new StringBuffer();

            try {
                URL url = new URL(updateUrl);
                reader = new BufferedReader(new InputStreamReader(url.openStream()));
                int read;
                char[] chars = new char[1024];
                while ((read = reader.read(chars)) != -1) {
                    if (progressMonitor.isCanceled()) {
                        cancel(true);
                        return null;
                    }
                    buffer.append(chars, 0, read);
                }
            } catch (IOException e) {
                System.err.println("checkForUpdates: " + e.getMessage()); //$NON-NLS-1$
            } finally {
                if (reader != null) {
                    reader.close();
                }
            }

            return buffer.toString();
        }

        @Override
        protected void done() {
            try {
                String json = get();
                Gson gson = new Gson();
                setKDXploreUpdate(gson.fromJson(json, KDXploreUpdate.class));
            } catch (CancellationException ignore) {
            } catch (InterruptedException ignore) {
            } catch (ExecutionException e) {
                Throwable cause = e.getCause();

                if (cause instanceof UnknownHostException) {
                    String site = extractSite(updateUrl);
                    ps.println(Msg.ERRMSG_UNABLE_TO_CONTACT_UPDATE_SITE(site));
                } else {
                    cause.printStackTrace(ps);
                }

                if (cause instanceof FileNotFoundException) {
                    FileNotFoundException fnf = (FileNotFoundException) cause;
                    if (updateUrl.equals(fnf.getMessage())) {
                        // Well maybe someone forgot to create the file on
                        // the server!
                        System.err.println("Maybe someone forgot to create the file!"); //$NON-NLS-1$
                        System.err.println(fnf.getMessage());

                        setKDXploreUpdate(new KDXploreUpdate(Msg.ERRMSG_PROBLEMS_CONTACTING_UPDATE_SERVER_1()));
                        return;
                    }
                }

                String msg = Msg.HTML_PROBLEMS_CONTACTING_UPDATE_2(StringUtil.htmlEscape(updateUrl),
                        cause.getClass().getSimpleName(), StringUtil.htmlEscape(cause.getMessage()));
                kdxploreUpdate = new KDXploreUpdate(msg);

                kdxploreUpdate.unknownHost = (cause instanceof UnknownHostException);
                return;
            }
        }

        private String extractSite(final String updateUrl) {
            String site = null;
            int spos = updateUrl.indexOf("://");
            if (spos > 0) {
                int epos = updateUrl.indexOf('/', spos + 1);
                if (epos > 0) {
                    site = updateUrl.substring(0, epos);
                }
            }
            if (site == null) {
                site = updateUrl;
            }
            return site;
        }
    };

    Closure<JDialog> onComplete = new Closure<JDialog>() {
        @Override
        public void execute(JDialog d) {
            if (!processReadUrlResult(updateUrl)) {
                d.dispose();
            } else {
                d.setVisible(true);
            }
        }
    };

    SwingWorkerCompletionWaiter waiter = new SwingWorkerCompletionWaiter(this, onComplete);
    worker.addPropertyChangeListener(waiter);

    worker.execute();
}

From source file:jshm.gui.GuiUtil.java

public static void openImageOrBrowser(final Frame owner, final String urlStr) {
    new SwingWorker<Void, Void>() {
        private BufferedImage image = null;
        private Throwable t = null;
        private boolean canceled = false;

        protected Void doInBackground() throws Exception {
            ProgressMonitor progress = null;

            try {
                // try to see if it's an image before downloading the
                // whole thing
                GetMethod method = new GetMethod(urlStr);
                Client.getHttpClient().executeMethod(method);
                Header h = method.getResponseHeader("Content-type");

                if (null != h && h.getValue().toLowerCase().startsWith("image/")) {
                    //                  jshm.util.TestTimer.start();
                    ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(owner, "Loading image...",
                            method.getResponseBodyAsStream());
                    progress = pmis.getProgressMonitor();
                    //                  System.out.println("BEFORE max: " + progress.getMaximum());
                    h = method.getResponseHeader("Content-length");

                    if (null != h) {
                        try {
                            progress.setMaximum(Integer.parseInt(h.getValue()));
                        } catch (NumberFormatException e) {
                        }// ww  w.  j a  v  a  2s  . c o  m
                    }
                    //                  System.out.println("AFTER max: " + progress.getMaximum());

                    progress.setMillisToDecideToPopup(250);
                    progress.setMillisToPopup(1000);

                    image = javax.imageio.ImageIO.read(pmis);
                    pmis.close();
                    //                  jshm.util.TestTimer.stop();
                    //                  jshm.util.TestTimer.start();
                    image = GraphicsUtilities.toCompatibleImage(image);
                    //                  jshm.util.TestTimer.stop();
                }

                method.releaseConnection();
            } catch (OutOfMemoryError e) {
                LOG.log(Level.WARNING, "OutOfMemoryError trying to load image", e);
                image = null; // make it open in browser
            } catch (Throwable e) {
                if (null != progress && progress.isCanceled()) {
                    canceled = true;
                } else {
                    t = e;
                }
            }

            return null;
        }

        public void done() {
            if (canceled)
                return;

            if (null == image) {
                if (null == t) {
                    // no error, just the url wasn't an image, so launch the browser
                    Util.openURL(urlStr);
                } else {
                    LOG.log(Level.WARNING, "Error opening image URL", t);
                    ErrorInfo ei = new ErrorInfo("Error", "Error opening image URL", null, null, t, null, null);
                    JXErrorPane.showDialog(owner, ei);
                }
            } else {
                SpInfoViewer viewer = new SpInfoViewer();
                viewer.setTitle(urlStr);
                viewer.setImage(image, true);
                viewer.setLocationRelativeTo(owner);
                viewer.setVisible(true);
            }
        }
    }.execute();
}

From source file:de.cismet.cids.custom.objecteditors.wunda_blau.WebDavPicturePanel.java

/**
 * DOCUMENT ME!/*from   w  w w .  ja va2  s .  c om*/
 *
 * @param   fileName  DOCUMENT ME!
 *
 * @return  DOCUMENT ME!
 *
 * @throws  Exception  DOCUMENT ME!
 */
private BufferedImage downloadImageFromWebDAV(final String fileName) throws Exception {
    final InputStream iStream = webdavHelper.getFileFromWebDAV(fileName, webdavDirectory,
            getConnectionContext());
    try {
        final ImageInputStream iiStream = ImageIO.createImageInputStream(iStream);
        final Iterator<ImageReader> itReader = ImageIO.getImageReaders(iiStream);
        if (itReader.hasNext()) {
            final ImageReader reader = itReader.next();
            final ProgressMonitor monitor = new ProgressMonitor(this, "Bild wird bertragen...", "", 0, 100);
            //            monitor.setMillisToPopup(500);
            reader.addIIOReadProgressListener(new IIOReadProgressListener() {

                @Override
                public void sequenceStarted(final ImageReader source, final int minIndex) {
                }

                @Override
                public void sequenceComplete(final ImageReader source) {
                }

                @Override
                public void imageStarted(final ImageReader source, final int imageIndex) {
                    monitor.setProgress(monitor.getMinimum());
                }

                @Override
                public void imageProgress(final ImageReader source, final float percentageDone) {
                    if (monitor.isCanceled()) {
                        try {
                            iiStream.close();
                        } catch (final IOException ex) {
                            // NOP
                        }
                    } else {
                        monitor.setProgress(Math.round(percentageDone));
                    }
                }

                @Override
                public void imageComplete(final ImageReader source) {
                    monitor.setProgress(monitor.getMaximum());
                }

                @Override
                public void thumbnailStarted(final ImageReader source, final int imageIndex,
                        final int thumbnailIndex) {
                }

                @Override
                public void thumbnailProgress(final ImageReader source, final float percentageDone) {
                }

                @Override
                public void thumbnailComplete(final ImageReader source) {
                }

                @Override
                public void readAborted(final ImageReader source) {
                    monitor.close();
                }
            });

            final ImageReadParam param = reader.getDefaultReadParam();
            reader.setInput(iiStream, true, true);
            final BufferedImage result;
            try {
                result = reader.read(0, param);
            } finally {
                reader.dispose();
                iiStream.close();
            }
            return result;
        } else {
            return null;
        }
    } finally {
        IOUtils.closeQuietly(iStream);
    }
}

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());// www . ja  v  a2 s . c om
    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;// w w w  .  ja  va 2  s.co  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. jav a2  s  . 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;
}

From source file:com.monead.semantic.workbench.SemanticWorkbench.java

/**
 * Expand all the nodes in the tree representation of the model
 * /*from www . ja v a 2 s . com*/
 * @return The final status to display
 */
private String expandAll() {
    int numNodes;
    ProgressMonitor progress;
    boolean canceled;
    final DefaultMutableTreeNode root = (DefaultMutableTreeNode) ontModelTree.getModel().getRoot();
    @SuppressWarnings("rawtypes")
    final Enumeration enumerateNodes = root.breadthFirstEnumeration();

    numNodes = 0;
    while (enumerateNodes.hasMoreElements()) {
        enumerateNodes.nextElement();
        ++numNodes;
    }

    LOGGER.debug("Expanding tree with row count: " + numNodes);

    progress = new ProgressMonitor(this, "Expanding Tree Nodes", "Starting node expansion", 0, numNodes);

    setStatus("Expanding all tree nodes");

    for (int row = 0; !progress.isCanceled() && row < numNodes; ++row) {
        progress.setProgress(row);
        if (row % 1000 == 0) {
            progress.setNote("Row " + row + " of " + numNodes);
        }

        ontModelTree.expandRow(row);
    }

    canceled = progress.isCanceled();

    progress.close();

    ontModelTree.scrollRowToVisible(0);

    if (!canceled) {
        // Select the tree view tab
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                tabbedPane.setSelectedIndex(TAB_NUMBER_TREE_VIEW);
            }
        });
    }

    return canceled ? "Tree node expansion canceled by user" : "Tree nodes expanded";
}

From source file:com.monead.semantic.workbench.SemanticWorkbench.java

/**
 * Add the classes to the tree view/*  w  w w.j a va2s  . c om*/
 * 
 * @see #addIndividualsToTree(OntClass, DefaultMutableTreeNode,
 *      ProgressMonitor)
 * 
 * @param classesNode
 *          The classes parent node in the tree
 * @param maxIndividualsPerClass
 *          The maximum number of individuals to display in each class
 * @param messagePrefix
 *          Prefix for display messages
 */
private void addClassesToTree(DefaultMutableTreeNode classesNode, int maxIndividualsPerClass,
        String messagePrefix) {
    ProgressMonitor progress = null;
    DefaultMutableTreeNode oneClassNode;
    List<OntClass> ontClasses;
    ExtendedIterator<OntClass> classesIterator;
    int classNumber;
    try {
        classesIterator = ontModel.listClasses();

        setStatus(messagePrefix + "... obtaining the list of classes");

        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("List of classes built");
        }
        ontClasses = new ArrayList<OntClass>();
        while (classesIterator.hasNext()) {
            ontClasses.add(classesIterator.next());
        }
        progress = new ProgressMonitor(this, "Create the model tree view", "Setting up the class list", 0,
                ontClasses.size());
        Collections.sort(ontClasses, new OntClassComparator());
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("List of classes sorted. Num classes:" + ontClasses.size());
        }

        classNumber = 0;
        for (OntClass ontClass : ontClasses) {
            setStatus(messagePrefix + " for class " + ontClass);

            if (MemoryWarningSystem.hasLatestAvailableTenuredGenAfterCollectionChanged(this)
                    && MemoryWarningSystem
                            .getLatestAvailableTenuredGenAfterCollection() < MINIMUM_BYTES_REQUIRED_FOR_TREE_BUILD) {
                throw new IllegalStateException(
                        "Insufficient memory available to complete building the tree (class iteration)");
            }

            if (progress.isCanceled()) {
                throw new RuntimeException("Tree model creation canceled by user");
            }

            progress.setNote(ontClass.toString());
            progress.setProgress(++classNumber);

            // Check whether class is to be skipped
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Check if class to be skipped: " + ontClass.getURI());
                for (String skipClass : classesToSkipInTree.keySet()) {
                    LOGGER.trace("Class to skip: " + skipClass + "  equal? "
                            + (skipClass.equals(ontClass.getURI())));
                }
            }
            if (filterEnableFilters.isSelected() && classesToSkipInTree.get(ontClass.getURI()) != null) {
                LOGGER.debug("Class to be skipped: " + ontClass.getURI());
                continue;
            }

            if (ontClass.isAnon()) {
                // Show anonymous classes based on configuration
                if (filterShowAnonymousNodes.isSelected()) {
                    oneClassNode = new DefaultMutableTreeNode(
                            new WrapperClass(ontClass.getId().getLabelString(), "[Anonymous class]", true));
                } else {
                    LOGGER.debug("Skip anonymous class: " + ontClass.getId().getLabelString());
                    continue;
                }
            } else {
                oneClassNode = new DefaultMutableTreeNode(new WrapperClass(ontClass.getLocalName(),
                        ontClass.getURI(), showFqnInTree.isSelected()));
                LOGGER.debug("Add class node: " + ontClass.getLocalName() + " (" + ontClass.getURI() + ")");
            }
            classesNode.add(oneClassNode);

            addIndividualsToTree(ontClass, oneClassNode, maxIndividualsPerClass, progress);
        }

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