Example usage for javax.swing ProgressMonitor ProgressMonitor

List of usage examples for javax.swing ProgressMonitor ProgressMonitor

Introduction

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

Prototype

public ProgressMonitor(Component parentComponent, Object message, String note, int min, int max) 

Source Link

Document

Constructs a graphic object that shows progress, typically by filling in a rectangular bar as the process nears completion.

Usage

From source file:ProgressMonitorExample.java

public ProgressMonitorExample() {
    super("Progress Monitor Demo");
    setSize(250, 100);//from  www .  j av  a 2  s.c  o  m
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    pbar = new ProgressMonitor(null, "Monitoring Progress", "Initializing . . .", 0, 100);

    // Fire a timer every once in a while to update the progress.
    Timer timer = new Timer(500, this);
    timer.start();
    setVisible(true);
}

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);/*w  w  w  .j  a v a 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);
    }
}

From source file:ProgressMonitorTest.java

public ProgressMonitorFrame() {
    setTitle("ProgressMonitorTest");
    setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

    // this text area holds the activity output
    textArea = new JTextArea();

    // set up a button panel
    JPanel panel = new JPanel();
    startButton = new JButton("Start");
    panel.add(startButton);/*from w  w  w  .  j  a va  2 s  .  c  o m*/

    add(new JScrollPane(textArea), BorderLayout.CENTER);
    add(panel, BorderLayout.SOUTH);

    // set up the button action

    startButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            startButton.setEnabled(false);
            final int MAX = 1000;

            // start activity
            activity = new SimulatedActivity(MAX);
            activity.execute();

            // launch progress dialog
            progressDialog = new ProgressMonitor(ProgressMonitorFrame.this, "Waiting for Simulated Activity",
                    null, 0, MAX);
            cancelMonitor.start();
        }
    });

    // set up the timer action

    cancelMonitor = new Timer(500, new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            if (progressDialog.isCanceled()) {
                activity.cancel(true);
                startButton.setEnabled(true);
            } else if (activity.isDone()) {
                progressDialog.close();
                startButton.setEnabled(true);
            } else {
                progressDialog.setProgress(activity.getProgress());
            }
        }
    });
}

From source file:mediathekplugin.MediathekProgramItem.java

private void openStream() {
    Thread streamThread = new Thread("Stream copy") {
        ProgressMonitor monitor = null;

        @Override/*  ww w.  j  a  v  a 2  s.  c o  m*/
        public void run() {
            try {
                monitor = new ProgressMonitor(MediathekPlugin.getInstance().getFrame(),
                        mLocalizer.msg("store", "Getting local stream copy..."), " ", 0, 3);
                monitor.setMillisToDecideToPopup(0);
                setNote(0, mLocalizer.ellipsisMsg("temp", "Starting flvstreamer"));
                File tempFile = File.createTempFile("mediathek", ".flv");
                String fileName = tempFile.toString();
                tempFile.delete();
                String streamParams = mUrl + " --flv " + fileName;
                ExecutionHandler streamer = new ExecutionHandler(streamParams, "flvstreamer");
                streamer.execute();
                DecimalFormat format = new DecimalFormat("0.00");
                setNote(1, mLocalizer.ellipsisMsg("wait", "Waiting for flvstreamer to get some data ({0} MB)",
                        format.format(0.0)));
                int time = 0;
                long fileSize = 0;
                try {
                    while (time < 20 && fileSize < 10 * 1024 * 1024 && !monitor.isCanceled()) {
                        Thread.sleep(500);
                        time++;
                        fileSize = tempFile.length();
                        double mb = fileSize / 1048576.0;
                        setNote(1, mLocalizer.ellipsisMsg("wait",
                                "Waiting for flvstreamer to get some data ({0} MB)", format.format(mb)));
                    }
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (!monitor.isCanceled()) {
                    setNote(2, mLocalizer.ellipsisMsg("player", "Starting player"));
                    ExecutionHandler player = new ExecutionHandler(fileName, "vlc");
                    player.execute();
                    setNote(3, "");
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (monitor != null) {
                monitor.close();
            }
        }

        private void setNote(final int progress, final String note) {
            try {
                UIThreadRunner.invokeAndWait(new Runnable() {

                    public void run() {
                        monitor.setProgress(progress);
                        monitor.setNote(note);
                    }
                });
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };
    streamThread.start();
}

From source file:ProgressMonitorDemo.java

/**
 * Invoked when the user presses the start button.
 *///from  ww  w  .ja  v  a2 s .co m
public void actionPerformed(ActionEvent evt) {
    progressMonitor = new ProgressMonitor(ProgressMonitorDemo.this, "Running a Long Task", "", 0, 100);
    progressMonitor.setProgress(0);
    task = new Task();
    task.addPropertyChangeListener(this);
    task.execute();
    startButton.setEnabled(false);
}

From source file:Main.java

/**
 * Called when the user presses the start button.
 */// w ww.j  a  v a 2s.  c  o  m
public void actionPerformed(ActionEvent evt) {
    progressMonitor = new ProgressMonitor(Main.this, "Running a Long Task", "", 0, task.getLengthOfTask());
    progressMonitor.setProgress(0);
    progressMonitor.setMillisToDecideToPopup(2 * ONE_SECOND);

    startButton.setEnabled(false);
    task.go();
    timer.start();
}

From source file:ProgressMonitorDemo.java

/**
 * Called when the user presses the start button.
 *///from w  ww  .ja v  a 2s . com
public void actionPerformed(ActionEvent evt) {
    progressMonitor = new ProgressMonitor(ProgressMonitorDemo.this, "Running a Long Task", "", 0,
            task.getLengthOfTask());
    progressMonitor.setProgress(0);
    progressMonitor.setMillisToDecideToPopup(2 * ONE_SECOND);

    startButton.setEnabled(false);
    task.go();
    timer.start();
}

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   ww  w.ja  v a2 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: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  ww.j av a 2 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.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$
    }/*from  w ww  .j  a  v  a  2 s  . 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();
}