Example usage for javax.swing ProgressMonitor setMillisToDecideToPopup

List of usage examples for javax.swing ProgressMonitor setMillisToDecideToPopup

Introduction

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

Prototype

public void setMillisToDecideToPopup(int millisToDecideToPopup) 

Source Link

Document

Specifies the amount of time to wait before deciding whether or not to popup a progress monitor.

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;//  w  ww .j a  v a  2  s  .c  o m
    int max = 100;
    JFrame component = new JFrame();
    ProgressMonitor pm = new ProgressMonitor(component, message, note, min, max);

    int millisToPopup = pm.getMillisToPopup(); // 2000

    int millisToDecideToPopup = pm.getMillisToDecideToPopup(); // 500

    pm.setMillisToPopup(0);
    pm.setMillisToDecideToPopup(0);

}

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 ww w .  ja  v a2s. 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: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 {//from w  ww  .  j  a  va  2s  . c  om
        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: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);//from   w  w  w .j a v a  2  s  .  co  m
    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: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.//from  w w w .  j  a va2s .  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);//from ww w. j  av a 2  s  .c  o  m
    UncompressTask task = new UncompressTask(progressMonitor);
    task.execute();
}

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

/**
 * /*  ww w .  j  av a 2 s . co  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:com.silverpeas.openoffice.windows.webdav.WebdavManager.java

/**
 * Get the ressource from the webdav server.
 *
 * @param uri the uri to the ressource.//from w  w w.  j  a  va2s  .  c om
 * @param lockToken the current lock token.
 * @return the path to the saved file on the filesystem.
 * @throws IOException
 */
public String getFile(URI uri, String lockToken) throws IOException {
    GetMethod method = executeGetFile(uri);
    String fileName = uri.getPath();
    fileName = fileName.substring(fileName.lastIndexOf('/') + 1);
    fileName = URLDecoder.decode(fileName, "UTF-8");
    UIManager.put("ProgressMonitor.progressText", MessageUtil.getMessage("download.file.title"));
    ProgressMonitorInputStream is = new ProgressMonitorInputStream(null,
            MessageUtil.getMessage("downloading.remote.file") + ' ' + fileName,
            new BufferedInputStream(method.getResponseBodyAsStream()));
    fileName = fileName.replace(' ', '_');
    ProgressMonitor monitor = is.getProgressMonitor();
    monitor.setMaximum(new Long(method.getResponseContentLength()).intValue());
    monitor.setMillisToDecideToPopup(0);
    monitor.setMillisToPopup(0);
    File tempDir = new File(System.getProperty("java.io.tmpdir"), "silver-" + System.currentTimeMillis());
    tempDir.mkdirs();
    File tmpFile = new File(tempDir, fileName);
    FileOutputStream fos = new FileOutputStream(tmpFile);
    byte[] data = new byte[64];
    int c = 0;
    try {
        while ((c = is.read(data)) > -1) {
            fos.write(data, 0, c);
        }
    } catch (InterruptedIOException ioinex) {
        logger.log(Level.INFO, "{0} {1}",
                new Object[] { MessageUtil.getMessage("info.user.cancel"), ioinex.getMessage() });
        unlockFile(uri, lockToken);
        System.exit(0);
    } finally {
        fos.close();
    }
    return tmpFile.getAbsolutePath();
}

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  . ja va 2 s . 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: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 va 2 s.  c om*/
        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();
    }
}