Example usage for javax.swing JOptionPane showMessageDialog

List of usage examples for javax.swing JOptionPane showMessageDialog

Introduction

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

Prototype

public static void showMessageDialog(Component parentComponent, Object message, String title, int messageType)
        throws HeadlessException 

Source Link

Document

Brings up a dialog that displays a message using a default icon determined by the messageType parameter.

Usage

From source file:com.projity.pm.graphic.gantt.Main.java

public static void main(String[] args) {
    System.setProperty("com.apple.mrj.application.apple.menu.about.name",
            Environment.getStandAlone() ? "OpenProj" : "Project-ON-Demand");
    System.setProperty("apple.laf.useScreenMenuBar", "true");
    Locale.setDefault(ConfigurationFile.getLocale());
    HashMap opts = ApplicationStartupFactory.extractOpts(args);
    String osName = System.getProperty("os.name").toLowerCase();
    if (osName.startsWith("linux")) {
        String javaExec = ConfigurationFile.getRunProperty("JAVA_EXE");
        //check jvm
        String javaVersion = System.getProperty("java.version");
        if (Environment.compareJavaVersion(javaVersion, "1.5") < 0) {
            String message = Messages.getStringWithParam("Text.badJavaVersion", javaVersion);
            if (javaExec != null && javaExec.length() > 0)
                message += "\n" + Messages.getStringWithParam("Text.javaExecutable",
                        new Object[] { javaExec, "JAVA_EXE", "$HOME/.openproj/run.conf" });
            if (!opts.containsKey("silentlyFail"))
                JOptionPane.showMessageDialog(null, message, Messages.getContextString("Title.ProjityError"),
                        JOptionPane.ERROR_MESSAGE);
            System.exit(64);//from  w  w w  .j a v  a2  s . c om
        }
        String javaVendor = System.getProperty("java.vendor");
        if (javaVendor == null || !(javaVendor.startsWith("Sun") || javaVendor.startsWith("IBM"))) {
            String message = Messages.getStringWithParam("Text.badJavaVendor", javaVendor);
            if (javaExec != null && javaExec.length() > 0)
                message += "\n" + Messages.getStringWithParam("Text.javaExecutable",
                        new Object[] { javaExec, "JAVA_EXE", "$HOME/.openproj/run.conf" });
            if (!opts.containsKey("silentlyFail"))
                JOptionPane.showMessageDialog(null, message, Messages.getContextString("Title.ProjityError"),
                        JOptionPane.ERROR_MESSAGE);
            System.exit(64);
        }
    }

    boolean newLook = false;
    //      HashMap opts = ApplicationStartupFactory.extractOpts(args); // allow setting menu look on command line - primarily for testing or webstart args
    log.info(opts);
    //      newLook = opts.get("menu") == null;

    Environment.setNewLook(newLook);
    //      if (!Environment.isNewLaf()) {
    //         try {
    //            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    //         } catch (Exception e) {
    //         }
    //      }
    ApplicationStartupFactory startupFactory = new ApplicationStartupFactory(opts); //put before to initialize standalone flag
    mainFrame = new MainFrame(Messages.getContextString("Text.ApplicationTitle"), null, null);
    boolean doWelcome = true; // to do see if project param exists in args
    startupFactory.instanceFromNewSession(mainFrame, doWelcome);
}

From source file:com.ln.gui.Main.java

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                createandshowgui();//  ww w  .ja v  a 2s.  c om
            } catch (Exception e) {
                //Kill&print on errors
                e.printStackTrace();
                JOptionPane.showMessageDialog(null, e.getStackTrace(), "Error", JOptionPane.WARNING_MESSAGE);
            }
        }
    });
}

From source file:flow.visibility.FlowMain.java

public static void main(String[] args) throws Exception {

    /************************************************************** 
     * Creating the Main GUI /* www . ja va2s. co m*/
     **************************************************************/

    final JDesktopPane desktop = new JDesktopPane();

    final JMenuBar mb = new JMenuBar();
    JMenu menu;

    /** Add File Menu to Open File and Save Result */

    menu = new JMenu("File");
    JMenuItem Open = new JMenuItem("Open");
    JMenuItem Save = new JMenuItem("Save");
    menu.add(Open);
    menu.add(Save);

    menu.addSeparator();
    JMenuItem Exit = new JMenuItem("Exit");
    menu.add(Exit);
    Exit.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    });

    mb.add(menu);

    /** Add Control Menu to Start and Stop Capture */

    menu = new JMenu("Control");
    JMenuItem Start = new JMenuItem("Start Capture");
    JMenuItem Stop = new JMenuItem("Stop Capture");
    menu.add(Start);
    Start.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            FlowDumper.main(false);
        }
    });

    menu.add(Stop);
    Stop.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            FlowDumper.main(true);
        }
    });

    mb.add(menu);

    /** Add Configuration Menu for Tapping and Display */

    menu = new JMenu("Configuration");
    JMenuItem Tapping = new JMenuItem("Tapping Configuration");
    JMenuItem Display = new JMenuItem("Display Configuration");
    menu.add(Tapping);
    Tapping.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            FlowTapping.main(null);
        }
    });
    menu.add(Display);

    mb.add(menu);

    /** Add Detail Menu for NetGrok Visualization and JEthereal Inspection */

    menu = new JMenu("Flow Detail");
    JMenuItem FlowVisual = new JMenuItem("Flow Visualization");
    JMenuItem FlowInspect = new JMenuItem("Flow Inspections");
    menu.add(FlowVisual);
    FlowVisual.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            NetworkView.main(null);
        }
    });
    menu.add(FlowInspect);
    FlowInspect.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Ethereal.main(null);
        }
    });
    mb.add(menu);

    /** Add Help Menu for Software Information */
    menu = new JMenu("Help");
    JMenuItem About = new JMenuItem("About");
    menu.add(About);
    About.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, "OF@TEIN Flow Visibility Tools @ 2015 by GIST",
                    "About the Software", JOptionPane.PLAIN_MESSAGE);
        }
    });
    mb.add(menu);

    /** Creating the main frame */
    JFrame frame = new JFrame("OF@TEIN Flow Visibility Tools");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());
    frame.add(desktop);
    frame.setJMenuBar(mb);
    frame.setSize(1215, 720);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

    /**Add Blank three (3) Internal Jframe*/

    /**Internal Frame from Flow Summary Chart*/
    JInternalFrame FlowStatistic = new JInternalFrame("Flow Statistic", true, true, true, true);
    FlowStatistic.setBounds(0, 0, 600, 330);
    ChartPanel chartPanel = new ChartPanel(createChart(null));
    chartPanel.setMouseZoomable(true, false);
    FlowStatistic.add(chartPanel);
    FlowStatistic.setVisible(true);
    desktop.add(FlowStatistic);

    /**Internal Frame from Flow Summary Text*/
    JInternalFrame FlowSummary = new JInternalFrame("Flow Summary", true, true, true, true);
    FlowSummary.setBounds(0, 331, 600, 329);
    JTextArea textArea = new JTextArea(50, 10);
    JScrollPane scrollPane = new JScrollPane(textArea);
    FlowSummary.add(scrollPane);
    FlowSummary.setVisible(true);
    desktop.add(FlowSummary);

    //JInternalFrame FlowInspection = new JInternalFrame("Flow Inspection", true, true, true, true);
    //FlowInspection.setBounds(601, 0, 600, 660);
    //JTextArea textArea2 = new JTextArea(50, 10);
    //JScrollPane scrollPane2 = new JScrollPane(textArea2);
    //FlowInspection.add(scrollPane2);
    //FlowInspection.setVisible(true);
    //desktop.add(FlowInspection);

    /**Internal Frame from Printing the Packet Sequence*/
    JInternalFrame FlowSequence = new JInternalFrame("Flow Sequence", true, true, true, true);
    FlowSequence.setBounds(601, 0, 600, 660);
    JTextArea textArea3 = new JTextArea(50, 10);
    JScrollPane scrollPane3 = new JScrollPane(textArea3);
    FlowSequence.add(scrollPane3);
    FlowSequence.setVisible(true);
    desktop.add(FlowSequence);

    /************************************************************** 
     * Update the Frame Regularly
     **************************************************************/

    /** Regularly update the Frame Content every 3 seconds */

    for (;;) {

        desktop.removeAll();
        desktop.add(FlowProcess.FlowStatistic());
        desktop.add(FlowProcess.FlowSummary());
        //desktop.add(FlowProcess.FlowInspection());
        desktop.add(FlowProcess.FlowSequence());
        desktop.revalidate();
        Thread.sleep(10000);

    }

}

From source file:fll.subjective.SubjectiveFrame.java

public static void main(final String[] args) {
    LogUtils.initializeLogging();/*from w w  w.ja  v  a  2s .c om*/

    Thread.setDefaultUncaughtExceptionHandler(new GuiExceptionHandler());

    // Use cross platform look and feel so that things look right all of the
    // time
    try {
        UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
    } catch (final ClassNotFoundException e) {
        LOGGER.warn("Could not find cross platform look and feel class", e);
    } catch (final InstantiationException e) {
        LOGGER.warn("Could not instantiate cross platform look and feel class", e);
    } catch (final IllegalAccessException e) {
        LOGGER.warn("Error loading cross platform look and feel", e);
    } catch (final UnsupportedLookAndFeelException e) {
        LOGGER.warn("Cross platform look and feel unsupported?", e);
    }

    try {
        final SubjectiveFrame frame = new SubjectiveFrame();
        frame.addWindowListener(new WindowAdapter() {
            @Override
            @SuppressFBWarnings(value = { "DM_EXIT" }, justification = "Exiting from main is OK")
            public void windowClosing(final WindowEvent e) {
                System.exit(0);
            }

            @Override
            @SuppressFBWarnings(value = { "DM_EXIT" }, justification = "Exiting from main is OK")
            public void windowClosed(final WindowEvent e) {
                System.exit(0);
            }
        });
        // should be able to watch for window closing, but hidden works
        frame.addComponentListener(new ComponentAdapter() {
            @Override
            @SuppressFBWarnings(value = { "DM_EXIT" }, justification = "Exiting from main is OK")
            public void componentHidden(final ComponentEvent e) {
                System.exit(0);
            }
        });
        GraphicsUtils.centerWindow(frame);
        frame.setVisible(true);
        frame.promptForFile();

    } catch (final Throwable e) {
        JOptionPane.showMessageDialog(null, "Unexpected error: " + e.getMessage(), "Error",
                JOptionPane.ERROR_MESSAGE);
        LOGGER.fatal("Unexpected error", e);
        System.exit(1);
    }
}

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.  jav  a2 s .  co m
        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:ch.admin.hermes.etl.load.HermesETLApplication.java

/**
 * Hauptprogramm//www .ja  va2 s . c  o  m
 * @param args Commandline Argumente
 */
public static void main(String[] args) {
    JFrame frame = null;
    try {
        // Crawler fuer Zugriff auf HERMES 5 Online Loesung initialiseren */
        crawler = new HermesOnlineCrawler();

        // CommandLine Argumente aufbereiten
        parseCommandLine(args);

        // Methoden Export (Variante Zuehlke) extrahieren
        System.out.println("load library " + model);
        ModelExtract root = new ModelExtract();
        root.extract(model);

        frame = createProgressDialog();
        // wird das XML Model von HERMES Online geholt - URL der Templates korrigieren
        if (scenario != null) {
            List<Workproduct> workproducts = (List<Workproduct>) root.getObjects().get("workproducts");
            for (Workproduct wp : workproducts)
                for (Template t : wp.getTemplate()) {
                    // Template beinhaltet kompletten URL - keine Aenderung
                    if (t.getUrl().toLowerCase().startsWith("http")
                            || t.getUrl().toLowerCase().startsWith("file"))
                        continue;
                    // Model wird ab Website geholte
                    if (model.startsWith("http"))
                        t.setUrl(crawler.getTemplateURL(scenario, t.getUrl()));
                    // Model ist lokal - Path aus model und relativem Path Template zusammenstellen
                    else {
                        File m = new File(model);
                        t.setUrl(m.getParentFile() + "/" + t.getUrl());
                    }
                }
        }

        // JavaScript - fuer Import in Fremdsystem
        if (script.endsWith(".js")) {
            final JavaScriptEngine js = new JavaScriptEngine();
            js.setObjects(root.getObjects());
            js.put("progress", progress);
            js.eval("function log( x ) { println( x ); progress.setString( x ); }");
            progress.setString("call main() in " + script);
            js.put(ScriptEngine.FILENAME, script);
            js.call(new InputStreamReader(new FileInputStream(script)), "main",
                    new Object[] { site, user, passwd });
        }
        // FreeMarker - fuer Umwandlungen nach HTML
        else if (script.endsWith(".ftl")) {
            FileOutputStream out = new FileOutputStream(
                    new File(script.substring(0, script.length() - 3) + "html "));
            int i = script.indexOf("templates");
            if (i >= 0)
                script = script.substring(i + "templates".length());
            MethodTransform transform = new MethodTransform();
            transform.transform(root.getObjects(), script, out);
            out.close();
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e.toString(), "Fehlerhafte Verarbeitung",
                JOptionPane.WARNING_MESSAGE);
        e.printStackTrace();
    }
    if (frame != null) {
        frame.setVisible(false);
        frame.dispose();
    }
    System.exit(0);
}

From source file:fll.scheduler.SchedulerUI.java

public static void main(final String[] args) {
    LogUtils.initializeLogging();/*from   w ww.j  a v  a 2  s. co  m*/

    Thread.setDefaultUncaughtExceptionHandler(new GuiExceptionHandler());

    // Use cross platform look and feel so that things look right all of the
    // time
    try {
        UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
    } catch (final ClassNotFoundException e) {
        LOGGER.warn("Could not find cross platform look and feel class", e);
    } catch (final InstantiationException e) {
        LOGGER.warn("Could not instantiate cross platform look and feel class", e);
    } catch (final IllegalAccessException e) {
        LOGGER.warn("Error loading cross platform look and feel", e);
    } catch (final UnsupportedLookAndFeelException e) {
        LOGGER.warn("Cross platform look and feel unsupported?", e);
    }

    try {
        final SchedulerUI frame = new SchedulerUI();

        frame.addWindowListener(new WindowAdapter() {
            @Override
            @SuppressFBWarnings(value = { "DM_EXIT" }, justification = "Exiting from main is OK")
            public void windowClosing(final WindowEvent e) {
                System.exit(0);
            }

            @Override
            @SuppressFBWarnings(value = { "DM_EXIT" }, justification = "Exiting from main is OK")
            public void windowClosed(final WindowEvent e) {
                System.exit(0);
            }
        });
        // should be able to watch for window closing, but hidden works
        frame.addComponentListener(new ComponentAdapter() {
            @Override
            @SuppressFBWarnings(value = { "DM_EXIT" }, justification = "Exiting from main is OK")
            public void componentHidden(final ComponentEvent e) {
                System.exit(0);
            }
        });

        GraphicsUtils.centerWindow(frame);

        frame.setVisible(true);
    } catch (final Exception e) {
        LOGGER.fatal("Unexpected error", e);
        JOptionPane.showMessageDialog(null,
                "An unexpected error occurred. Please send the log file and a description of what you were doing to the developer. Error message: "
                        + e.getMessage(),
                "Error", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:com.tiempometa.muestradatos.JMuestraDatos.java

/**
 * Application entry point//from   w w  w . ja va2  s. co  m
 * 
 * @param args
 */
public static void main(String[] args) {
    try {
        // Set System L&F
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (UnsupportedLookAndFeelException e) {
        // handle exception
    } catch (ClassNotFoundException e) {
        // handle exception
    } catch (InstantiationException e) {
        // handle exception
    } catch (IllegalAccessException e) {
        // handle exception
    }

    logger.info(systemProperties.java_version);
    logger.info(systemProperties.arch_data_model);
    logger.info(systemProperties.java_home);
    logger.info(systemProperties.user_dir);
    if (systemProperties.arch_data_model.equals(InstallUtils.AMD64)) {
        JOptionPane.showMessageDialog(null, "Se requiere Java 32bits para ejecutar este programa",
                "Systema de 64 bits", JOptionPane.WARNING_MESSAGE);
        JInstaller installer = new JInstaller(null);
        installer.setVisible(true);
    } else {
        if (!(systemProperties.getJava_version().startsWith("1.6")
                || systemProperties.getJava_version().startsWith("1.7"))) {
            JOptionPane.showMessageDialog(null, "Se requiere Java 6 o 7 para ejecutar este programa",
                    "Versin de Java no soportada", JOptionPane.WARNING_MESSAGE);
            JInstaller installer = new JInstaller(null);
            installer.setVisible(true);
        } else {
            JMuestraDatos reader = new JMuestraDatos();
            reader.setVisible(true);
        }
    }
}

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);/*  w  w  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: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.ja  v a2s  .  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);
}