Example usage for javax.swing ProgressMonitor setProgress

List of usage examples for javax.swing ProgressMonitor setProgress

Introduction

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

Prototype

@SuppressWarnings("deprecation")
public void setProgress(int nv) 

Source Link

Document

Indicate the progress of the operation being monitored.

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;/*from  ww w .j  ava2s.  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:kindleclippings.word.QuizletSync.java

public static void main(String[] args) throws IOException, JSONException, URISyntaxException,
        InterruptedException, BackingStoreException, BadLocationException {

    JFileChooser fc = new JFileChooser();
    fc.setFileFilter(new FileNameExtensionFilter("Word documents", "doc", "rtf", "txt"));
    fc.setMultiSelectionEnabled(true);//from   www  .ja  va 2s  .c o m
    int result = fc.showOpenDialog(null);
    if (result != JFileChooser.APPROVE_OPTION) {
        return;
    }
    File[] clf = fc.getSelectedFiles();
    if (clf == null || clf.length == 0)
        return;

    ProgressMonitor progress = new ProgressMonitor(null, "QuizletSync", "loading notes files", 0, 100);
    progress.setMillisToPopup(0);
    progress.setMillisToDecideToPopup(0);
    progress.setProgress(0);
    try {

        progress.setNote("checking Quizlet account");
        progress.setProgress(5);

        Preferences prefs = kindleclippings.quizlet.QuizletSync.getPrefs();

        QuizletAPI api = new QuizletAPI(prefs.get("access_token", null));

        Collection<TermSet> sets = null;
        try {
            progress.setNote("checking Quizlet library");
            progress.setProgress(10);
            sets = api.getSets(prefs.get("user_id", null));
        } catch (IOException e) {
            if (e.toString().contains("401")) {
                // Not Authorized => Token has been revoked
                kindleclippings.quizlet.QuizletSync.clearPrefs();
                prefs = kindleclippings.quizlet.QuizletSync.getPrefs();
                api = new QuizletAPI(prefs.get("access_token", null));
                sets = api.getSets(prefs.get("user_id", null));
            } else {
                throw e;
            }
        }

        progress.setProgress(15);
        progress.setMaximum(15 + clf.length * 10);
        progress.setNote("uploading new notes");

        int pro = 15;

        int addedSets = 0;
        int updatedTerms = 0;
        int updatedSets = 0;

        for (File f : clf) {
            progress.setProgress(pro);
            List<Clipping> clippings = readClippingsFile(f);

            if (clippings == null) {
                pro += 10;
                continue;
            }

            if (clippings.isEmpty()) {
                pro += 10;
                continue;
            }

            if (clippings.size() < 2) {
                pro += 10;
                continue;
            }

            String book = clippings.get(0).getBook();
            progress.setNote(book);

            TermSet termSet = null;
            String x = book.toLowerCase().replaceAll("\\W", "");

            for (TermSet t : sets) {
                if (t.getTitle().toLowerCase().replaceAll("\\W", "").equals(x)) {
                    termSet = t;
                    break;
                }
            }

            if (termSet == null) {

                addSet(api, book, clippings);
                addedSets++;
                pro += 10;
                continue;
            }

            // compare against existing terms
            boolean hasUpdated = false;
            for (Clipping cl : clippings) {
                if (!kindleclippings.quizlet.QuizletSync.checkExistingTerm(cl, termSet)) {
                    kindleclippings.quizlet.QuizletSync.addTerm(api, termSet, cl);
                    updatedTerms++;
                    hasUpdated = true;
                }
            }

            pro += 10;

            if (hasUpdated)
                updatedSets++;

        }

        if (updatedTerms == 0 && addedSets == 0) {
            JOptionPane.showMessageDialog(null, "Done.\nNo new data was uploaded", "QuizletSync",
                    JOptionPane.OK_OPTION);
        } else {
            if (addedSets > 0) {
                JOptionPane.showMessageDialog(null,
                        String.format("Done.\nCreated %d new sets and added %d cards to %d existing sets",
                                addedSets, updatedSets, updatedTerms),
                        "QuizletSync", JOptionPane.OK_OPTION);
            } else {
                JOptionPane.showMessageDialog(null,
                        String.format("Done.\nAdded %d cards to %d existing sets", updatedTerms, updatedSets),
                        "QuizletSync", JOptionPane.OK_OPTION);
            }
        }
    } finally {
        progress.close();
    }

    System.exit(0);
}

From source file:kindleclippings.quizlet.QuizletSync.java

public static void main(String[] args)
        throws IOException, JSONException, URISyntaxException, InterruptedException, BackingStoreException {

    ProgressMonitor progress = new ProgressMonitor(null, "QuizletSync", "loading Kindle clippings file", 0,
            100);/*  w ww .j a v  a2  s  . c  om*/
    progress.setMillisToPopup(0);
    progress.setMillisToDecideToPopup(0);
    progress.setProgress(0);
    try {

        Map<String, List<Clipping>> books = readClippingsFile();

        if (books == null)
            return;

        if (books.isEmpty()) {
            JOptionPane.showMessageDialog(null, "no clippings to be uploaded", "QuizletSync",
                    JOptionPane.OK_OPTION);
            return;
        }
        progress.setNote("checking Quizlet account");
        progress.setProgress(5);

        Preferences prefs = getPrefs();

        QuizletAPI api = new QuizletAPI(prefs.get("access_token", null));

        Collection<TermSet> sets = null;
        try {
            progress.setNote("checking Quizlet library");
            progress.setProgress(10);
            sets = api.getSets(prefs.get("user_id", null));
        } catch (IOException e) {
            if (e.toString().contains("401")) {
                // Not Authorized => Token has been revoked
                clearPrefs();
                prefs = getPrefs();
                api = new QuizletAPI(prefs.get("access_token", null));
                sets = api.getSets(prefs.get("user_id", null));
            } else {
                throw e;
            }
        }

        progress.setProgress(15);
        progress.setMaximum(15 + books.size());
        progress.setNote("uploading new notes");

        Map<String, TermSet> indexedSets = new HashMap<String, TermSet>(sets.size());

        for (TermSet t : sets) {
            indexedSets.put(t.getTitle(), t);
        }

        int pro = 15;
        int createdSets = 0;
        int createdTerms = 0;
        int updatedTerms = 0;
        for (List<Clipping> c : books.values()) {

            String book = c.get(0).getBook();
            progress.setNote(book);
            progress.setProgress(pro++);

            TermSet termSet = indexedSets.get(book);
            if (termSet == null) {
                if (c.size() < 2) {
                    System.err.println("ignored [" + book + "] (need at least two notes)");
                    continue;
                }

                addSet(api, book, c);
                createdSets++;
                createdTerms += c.size();
                continue;
            }
            // compare against existing terms
            for (Clipping cl : c) {
                if (!checkExistingTerm(cl, termSet)) {
                    addTerm(api, termSet, cl);
                    updatedTerms++;
                }
            }
        }
        progress.setProgress(pro++);

        if (createdSets == 0 && updatedTerms == 0) {
            JOptionPane.showMessageDialog(null, "Done.\nNo new data was uploaded", "QuizletSync",
                    JOptionPane.OK_OPTION);
        } else if (createdSets > 0) {
            JOptionPane.showMessageDialog(null,
                    String.format(
                            "Done.\nCreated %d new sets with %d cards, and added %d cards to existing sets",
                            createdSets, createdTerms, updatedTerms),
                    "QuizletSync", JOptionPane.OK_OPTION);
        } else {
            JOptionPane.showMessageDialog(null,
                    String.format("Done.\nAdded %d cards to existing sets", updatedTerms), "QuizletSync",
                    JOptionPane.OK_OPTION);
        }
    } finally {
        progress.close();
    }

    System.exit(0);
}

From source file:kevin.gvmsgarch.App.java

public static void main(String[] args) throws HttpException, IOException, ParserConfigurationException,
        SAXException, XPathExpressionException, JSONException, InterruptedException {
    System.out.println("Google Voice Message Archiver");
    System.out.println("Copyright (C) 2013 Kevin Carter");

    System.out.println("This program comes with ABSOLUTELY NO WARRANTY");
    System.out.println("This is free software, and you are welcome to redistribute it");
    System.out.println("under certain conditions. See the LICENSE file or");
    System.out.println("http://www.gnu.org/licenses/gpl-3.0.txt for details");
    try {/* w  w w  .j  a  v a 2s. com*/
        HttpClient c = new HttpClient();

        String userName = getUserName();
        String password = getPassword();

        int locationChosenIndex = JOptionPane.CLOSED_OPTION;
        if (password != null) {
            locationChosenIndex = JOptionPane.showOptionDialog(null, "Message source", "",
                    JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null,
                    Worker.ListLocation.values(), Worker.ListLocation.inbox);
        }
        if (locationChosenIndex != JOptionPane.CLOSED_OPTION) {
            int modeChosenIndex = 0;
            Worker.ArchiveMode modeChosen = null;
            Worker.ListLocation location = Worker.ListLocation.values()[locationChosenIndex];
            Worker.ArchiveMode[] availableModes = location.getAllowedModes();
            if (availableModes.length == 1) {
                modeChosen = availableModes[0];
            } else {
                modeChosenIndex = JOptionPane.showOptionDialog(null, "Operation mode", "",
                        JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, availableModes,
                        Worker.ArchiveMode.archive);
                if (modeChosenIndex != JOptionPane.CLOSED_OPTION) {
                    modeChosen = availableModes[modeChosenIndex];
                }
            }

            ContactFilter filter = null;
            if (modeChosenIndex != JOptionPane.CLOSED_OPTION
                    && locationChosenIndex != JOptionPane.CLOSED_OPTION) {
                filter = buildFilter();
            }

            if (modeChosenIndex != JOptionPane.CLOSED_OPTION && locationChosenIndex != JOptionPane.CLOSED_OPTION
                    && filter != null && areYouSure(modeChosen, location, filter)) {
                assert modeChosen != null : "ZOMG";
                String authToken = getToken(userName, password);
                String rnrse = getRnrse(authToken);

                final ProgressMonitor pm = new ProgressMonitor(null, "Working", "", 0,
                        App.parseMsgsLeft(extractInboxJson(authToken, location, 1)));
                pm.setMillisToDecideToPopup(0);
                pm.setMillisToPopup(0);

                Worker worker = new Worker(authToken, rnrse, pm, modeChosen, location, filter);
                worker.addPropertyChangeListener(new ProgressPropertyChangeListener(pm));
                pm.setProgress(0);
                worker.execute();
            }
        }
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, ex.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:hermes.impl.LoaderSupport.java

/**
 * Return ClassLoader given the list of ClasspathConfig instances. The
 * resulting loader can then be used to instantiate providers from those
 * libraries./*w  w w. j  av a2 s .  c o  m*/
 */
static List lookForFactories(final List loaderConfigs, final ClassLoader baseLoader) throws IOException {
    final List rval = new ArrayList();

    for (Iterator iter = loaderConfigs.iterator(); iter.hasNext();) {
        final ClasspathConfig lConfig = (ClasspathConfig) iter.next();

        if (lConfig.getFactories() != null) {
            log.debug("using cached " + lConfig.getFactories());

            for (StringTokenizer tokens = new StringTokenizer(lConfig.getFactories(), ","); tokens
                    .hasMoreTokens();) {
                rval.add(tokens.nextToken());
            }
        } else if (lConfig.isNoFactories()) {
            log.debug("previously scanned " + lConfig.getJar());
        } else {
            Runnable r = new Runnable() {
                public void run() {
                    final List localFactories = new ArrayList();
                    boolean foundFactory = false;
                    StringBuffer factoriesAsString = null;

                    try {
                        log.debug("searching " + lConfig.getJar());

                        ClassLoader l = createClassLoader(loaderConfigs, baseLoader);
                        JarFile jarFile = new JarFile(lConfig.getJar());
                        ProgressMonitor monitor = null;
                        int entryNumber = 0;

                        if (HermesBrowser.getBrowser() != null) {
                            monitor = new ProgressMonitor(HermesBrowser.getBrowser(),
                                    "Looking for factories in " + lConfig.getJar(), "Scanning...", 0,
                                    jarFile.size());
                            monitor.setMillisToDecideToPopup(0);
                            monitor.setMillisToPopup(0);
                            monitor.setProgress(0);
                        }

                        for (Enumeration iter = jarFile.entries(); iter.hasMoreElements();) {
                            ZipEntry entry = (ZipEntry) iter.nextElement();
                            entryNumber++;

                            if (monitor != null) {
                                monitor.setProgress(entryNumber);
                                monitor.setNote("Checking entry " + entryNumber + " of " + jarFile.size());
                            }

                            if (entry.getName().endsWith(".class")) {
                                String s = entry.getName().substring(0, entry.getName().indexOf(".class"));

                                s = s.replaceAll("/", ".");

                                try {
                                    if (s.startsWith("hermes.browser") || s.startsWith("hermes.impl")
                                            || s.startsWith("javax.jms")) {
                                        // NOP
                                    } else {
                                        Class clazz = l.loadClass(s);

                                        if (!clazz.isInterface()) {

                                            if (implementsOrExtends(clazz, ConnectionFactory.class)) {

                                                foundFactory = true;
                                                localFactories.add(s);

                                                if (factoriesAsString == null) {
                                                    factoriesAsString = new StringBuffer();
                                                    factoriesAsString.append(clazz.getName());
                                                } else {
                                                    factoriesAsString.append(",").append(clazz.getName());
                                                }
                                                log.debug("found " + clazz.getName());
                                            }
                                        }

                                        /**
                                         * TODO: remove Class clazz = l.loadClass(s);
                                         * Class[] interfaces = clazz.getInterfaces();
                                         * for (int i = 0; i < interfaces.length; i++) {
                                         * if
                                         * (interfaces[i].equals(TopicConnectionFactory.class) ||
                                         * interfaces[i].equals(QueueConnectionFactory.class) ||
                                         * interfaces[i].equals(ConnectionFactory.class)) {
                                         * foundFactory = true; localFactories.add(s);
                                         * if (factoriesAsString == null) {
                                         * factoriesAsString = new
                                         * StringBuffer(clazz.getName()); } else {
                                         * factoriesAsString.append(",").append(clazz.getName()); }
                                         * log.debug("found " + clazz.getName()); } }
                                         */
                                    }
                                } catch (Throwable t) {
                                    // NOP
                                }
                            }
                        }
                    } catch (IOException e) {
                        log.error("unable to access jar/zip " + lConfig.getJar() + ": " + e.getMessage(), e);
                    }

                    if (!foundFactory) {
                        lConfig.setNoFactories(true);
                    } else {
                        lConfig.setFactories(factoriesAsString.toString());
                        rval.addAll(localFactories);
                    }

                }
            };

            r.run();

        }
    }

    return rval;
}

From source file:com.frostwire.gui.updates.PortableUpdater.java

public void update() {
    ProgressMonitor progressMonitor = new ProgressMonitor(GUIMediator.getAppFrame(),
            I18n.tr("Uncompressing files"), "", 0, 100);
    progressMonitor.setMillisToDecideToPopup(0);
    progressMonitor.setMillisToPopup(0);
    progressMonitor.setProgress(0);
    UncompressTask task = new UncompressTask(progressMonitor);
    task.execute();//from   w w w .j  ava 2s  .  co  m
}

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 w w  .j  a  va2s.  c o  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:hermes.store.schema.DefaultJDBCAdapter.java

private void executeStatements(Connection connection, String[] statements) throws SQLException {
    final StringBuffer message = new StringBuffer();
    ProgressMonitor progressMonitor = null;

    if (HermesBrowser.getBrowser() != null) {
        progressMonitor = new ProgressMonitor(HermesBrowser.getBrowser(), "Initialising message stores... ",
                "Connecting...", 0, statements.length);

        progressMonitor.setMillisToDecideToPopup(100);
        progressMonitor.setMillisToPopup(400);
    }//from  w w w  . j  a  v  a 2  s .co  m

    final QueryRunner runner = new QueryRunner();

    for (int i = 0; i < statements.length; i++) {
        try {
            log.debug("executing: " + statements[i]);

            if (progressMonitor != null) {
                progressMonitor.setProgress(statements.length);
                progressMonitor.setNote("Executing statement " + i + " of " + statements.length);
            }

            runner.update(connection, statements[i]);
        } catch (SQLException ex) {
            log.error(ex.getMessage());
        }
    }
}

From source file:fr.crnan.videso3d.ihm.PLNSPanel.java

/**
 * //from   w  ww  .  j av  a2s.  c o  m
 * @param path
 *            Chemin vers la base de donnes
 */
public PLNSPanel(final String path) {
    this.setLayout(new BorderLayout());

    this.add(createToolbar(), BorderLayout.NORTH);

    desktop = new TilingDesktopPane();
    desktop.setPreferredSize(new Dimension(800, 600));
    this.add(desktop);

    chartPanels = new ArrayList<ChartPanel>();

    final ProgressMonitor progressMonitorT = new ProgressMonitor(this, "Extraction des donnes", "", 0, 100,
            false, true, false);
    progressMonitorT.setMillisToDecideToPopup(0);
    progressMonitorT.setMillisToPopup(0);
    progressMonitorT.setNote("Extraction des fichiers compresss...");

    plnsAnalyzer = new PLNSAnalyzer();

    //au cas o il faille importer les donnes, on coute le ProgressSupport et on ne lance la cration de la fentre qu' la fin
    plnsAnalyzer.addPropertyChangeListener(new PropertyChangeListener() {

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if (evt.getPropertyName().equals(ProgressSupport.TASK_STARTS)) {

            } else if (evt.getPropertyName().equals(ProgressSupport.TASK_PROGRESS)) {
                progressMonitorT.setProgress((Integer) evt.getNewValue());
            } else if (evt.getPropertyName().equals(ProgressSupport.TASK_INFO)) {
                progressMonitorT.setNote((String) evt.getNewValue());
            } else if (evt.getPropertyName().equals(ProgressSupport.TASK_ENDS)) {
                createIHM();
            }
        }
    });

    new SwingWorker<Void, Void>() {

        @Override
        protected Void doInBackground() throws Exception {
            plnsAnalyzer.setPath(path);
            return null;
        }
    }.execute();
}

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  w w . j a va  2  s .  c o m
        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);
    }
}