Example usage for javax.swing JOptionPane showOptionDialog

List of usage examples for javax.swing JOptionPane showOptionDialog

Introduction

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

Prototype

@SuppressWarnings("deprecation")
public static int showOptionDialog(Component parentComponent, Object message, String title, int optionType,
        int messageType, Icon icon, Object[] options, Object initialValue) throws HeadlessException 

Source Link

Document

Brings up a dialog with a specified icon, where the initial choice is determined by the initialValue parameter and the number of choices is determined by the optionType parameter.

Usage

From source file:org.tridas.io.gui.control.TricycleController.java

public void startup(MVCEvent argEvent) {
    if (view == null) {
        view = new MainWindow(TricycleModelLocator.getInstance().getTricycleModel());
        TricycleModelLocator.getInstance().setMainWindow(view);
        if (argEvent instanceof StartupEvent) {
            if (((StartupEvent) argEvent).exitOnClose) {
                view.setDefaultCloseOperation(3);
            } else {
                view.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
            }/*  w  w  w .ja v a 2 s  . c om*/
        }
        view.setVisible(true);
        ToolTipManager.sharedInstance().setDismissDelay(10000);
    } else {
        view.setVisible(true);
    }

    TricycleModel model = TricycleModelLocator.getInstance().getTricycleModel();

    // Check to see if we should auto update
    if (TricycleModelLocator.getInstance().isAutoUpdate()) {
        model.setAutoUpdate(true);
        CheckForUpdateEvent event = new CheckForUpdateEvent(false);
        event.dispatch();
    }

    // Check to see if tracking should be set
    if (TricycleModelLocator.getInstance().isTracking()) {
        model.setTracking(true);
    }

    // Check to see if we need to ask permission about tracking
    if (!model.isTracking() && !TricycleModelLocator.getInstance().isDontAskTracking()) {
        String[] options = new String[] { I18n.getText("view.popup.tracking.askLater"),
                I18n.getText("view.popup.tracking.no"), I18n.getText("view.popup.tracking.yes")

        };
        ImageIcon aicon = new ImageIcon(IOUtils.getFileInJarURL("icons/128x128/application.png"));

        int response = JOptionPane.showOptionDialog(view,
                WordUtils.wrap(I18n.getText("view.popup.tracking.question"), 50),
                I18n.getText("view.popup.tracking.title"), JOptionPane.YES_NO_CANCEL_OPTION,
                JOptionPane.QUESTION_MESSAGE, aicon, options, options[0]);

        if (response == 2) {
            model.setTracking(true);
            TricycleModelLocator.getInstance().setDontAskTracking(true);
        } else if (response == 1) {
            model.setTracking(false);
            TricycleModelLocator.getInstance().setDontAskTracking(true);
        } else if (response == 0) {
            model.setTracking(false);
            TricycleModelLocator.getInstance().setDontAskTracking(false);
        }
    }
}

From source file:org.ut.biolab.medsavant.client.project.ProjectController.java

/**
 * Give user the option to publish unpublished changes or cancel them.
 * @return <code>true</code> if the user is able to proceed (i.e. they haven't cancelled or logged out)
 *///w  w  w . j a v  a 2 s  .c  o m
public boolean promptToPublish(ProjectDetails pd) {
    Object[] options = new Object[] { "Publish", "Delete (Undo Changes)", "Cancel" };
    int option = JOptionPane.showOptionDialog(null,
            "<HTML>Publishing this table will log all users out of MedSavant, and restart the program. <BR>Are you sure you want to proceed?</HTML>",
            "Confirm", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,
            options[2]);
    if (option == JOptionPane.NO_OPTION) {
        try {
            MedSavantClient.VariantManager.cancelPublish(LoginController.getSessionID(), pd.getProjectID(),
                    pd.getReferenceID(), pd.getUpdateID());
            return true;
        } catch (Exception ex) {
            ClientMiscUtils.reportError("Error cancelling publication of variants: %s", ex);
        }
    } else if (option == JOptionPane.YES_OPTION) {
        try {
            publishVariants(LoginController.getSessionID(), pd.getProjectID(), pd.getReferenceID(),
                    pd.getUpdateID(), null);
            //MedSavantClient.VariantManager.publishVariants(LoginController.getSessionID(), pd.getProjectID(), pd.getReferenceID(), pd.getUpdateID());
            //MedSavantClient.restart(null);
            //LoginController.getInstance().logout();
        } catch (Exception ex) {
            ClientMiscUtils.reportError("Error publishing variants: %s", ex);
        }
    }
    return false;
}

From source file:org.yccheok.jstock.gui.JStock.java

/**
 * @param args the command line arguments
 *//*from w w w .ja v a 2 s  .  c o m*/
public static void main(String args[]) {
    /***********************************************************************
     * UI Manager initialization via JStockOptions.
     **********************************************************************/
    final JStockOptions jStockOptions = getJStockOptionsViaXML();

    // OSX menu bar at top.
    if (Utils.isMacOSX()) {
        System.setProperty("apple.laf.useScreenMenuBar", "true");
        System.setProperty("apple.awt.brushMetalLook", "true");
    }

    boolean uiManagerLookAndFeelSuccess = false;
    try {
        String lookNFeel = jStockOptions.getLooknFeel();
        if (null != lookNFeel) {
            UIManager.setLookAndFeel(lookNFeel);
            uiManagerLookAndFeelSuccess = true;
        }
    } catch (java.lang.ClassNotFoundException | java.lang.InstantiationException
            | java.lang.IllegalAccessException | javax.swing.UnsupportedLookAndFeelException exp) {
        log.error(null, exp);
    }

    if (!uiManagerLookAndFeelSuccess) {
        String className = Utils.setDefaultLookAndFeel();
        if (null != className) {
            final String lookNFeel = jStockOptions.getLooknFeel();
            // When jStockOptions.getLookNFeel returns null, it means we wish
            // to use system default value. Hence, don't overwrite the null value,
            // so that we can use the same jStockOptions, across different
            // platforms.
            if (lookNFeel != null) {
                jStockOptions.setLooknFeel(className);
            }
        }
    }

    /***********************************************************************
     * Ensure correct localization.
     **********************************************************************/
    // This global effect, should just come before anything else, 
    // after we get an instance of JStockOptions.
    Locale.setDefault(jStockOptions.getLocale());

    /***********************************************************************
     * Single application instance enforcement.
     **********************************************************************/
    if (false == AppLock.lock()) {
        final int choice = JOptionPane.showOptionDialog(null,
                MessagesBundle.getString("warning_message_running_2_jstock"),
                MessagesBundle.getString("warning_title_running_2_jstock"), JOptionPane.YES_NO_OPTION,
                JOptionPane.WARNING_MESSAGE, null,
                new String[] { MessagesBundle.getString("yes_button_running_2_jstock"),
                        MessagesBundle.getString("no_button_running_2_jstock") },
                MessagesBundle.getString("no_button_running_2_jstock"));
        if (choice != JOptionPane.YES_OPTION) {
            System.exit(0);
            return;
        }
    }

    // Avoid "JavaFX IllegalStateException when disposing JFXPanel in Swing"
    // http://stackoverflow.com/questions/16867120/javafx-illegalstateexception-when-disposing-jfxpanel-in-swing
    Platform.setImplicitExit(false);

    // As ProxyDetector is affected by system properties
    // http.proxyHost, we are forced to initialized ProxyDetector right here,
    // before we manually change the system properties according to
    // JStockOptions.
    ProxyDetector.getInstance();

    /***********************************************************************
     * Apply large font if possible.
     **********************************************************************/
    if (jStockOptions.useLargeFont()) {
        java.util.Enumeration keys = UIManager.getDefaults().keys();
        while (keys.hasMoreElements()) {
            Object key = keys.nextElement();
            Object value = UIManager.get(key);
            if (value != null && value instanceof javax.swing.plaf.FontUIResource) {
                javax.swing.plaf.FontUIResource fr = (javax.swing.plaf.FontUIResource) value;
                UIManager.put(key, new javax.swing.plaf.FontUIResource(
                        fr.deriveFont((float) fr.getSize2D() * (float) Constants.FONT_ENLARGE_FACTOR)));
            }
        }
    }

    /***********************************************************************
     * GA tracking.
     **********************************************************************/
    GA.trackAsynchronously("main");

    java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            final JStock mainFrame = JStock.instance();

            // We need to first assign jStockOptions to mainFrame, as during
            // Utils.migrateXMLToCSVPortfolios, we will be accessing mainFrame's
            // jStockOptions.
            mainFrame.initJStockOptions(jStockOptions);

            mainFrame.init();
            mainFrame.setVisible(true);
            mainFrame.updateDividerLocation();
            mainFrame.requestFocusOnJComboBox();
        }
    });
}

From source file:org.yccheok.jstock.gui.MainFrame.java

/**
 * @param args the command line arguments
 *//*from   w  w w  . j a  v  a2s.c om*/
public static void main(String args[]) {
    if (false == AppLock.lock()) {
        final int choice = JOptionPane.showOptionDialog(null,
                MessagesBundle.getString("warning_message_running_2_jstock"),
                MessagesBundle.getString("warning_title_running_2_jstock"), JOptionPane.YES_NO_OPTION,
                JOptionPane.WARNING_MESSAGE, null,
                new String[] { MessagesBundle.getString("yes_button_running_2_jstock"),
                        MessagesBundle.getString("no_button_running_2_jstock") },
                MessagesBundle.getString("no_button_running_2_jstock"));
        if (choice != JOptionPane.YES_OPTION) {
            System.exit(0);
            return;
        }
    }

    // As ProxyDetector is affected by system properties
    // http.proxyHost, we are forced to initialized ProxyDetector right here,
    // before we manually change the system properties according to
    // JStockOptions.
    ProxyDetector.getInstance();

    Utils.setDefaultLookAndFeel();

    final String[] _args = args;

    java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            final MainFrame mainFrame = MainFrame.getInstance();
            final JStockOptions jStockOptions = getJStockOptions(_args);
            // This global effect, should just come before anything else, 
            // after we get an instance of JStockOptions.
            Locale.setDefault(jStockOptions.getLocale());

            // We need to first assign jStockOptions to mainFrame, as during
            // Utils.migrateXMLToCSVPortfolios, we will be accessing mainFrame's
            // jStockOptions.
            mainFrame.initJStockOptions(jStockOptions);

            mainFrame.init();
            mainFrame.setVisible(true);
            mainFrame.updateDividerLocation();
            mainFrame.requestFocusOnJComboBox();
        }
    });
}

From source file:osmcb.program.EnvironmentSetup.java

/**
 * Note: This method has to be called before {@link OSMCBSettings#loadOrQuit()}. Therefore no localization is available at this point.
 *///from ww w . jav  a2  s.  co  m
public static void checkSettingsSetup() {
    checkDirectory(DirectoryManager.userSettingsDir, "user settings", true);
    if (!OSMCBSettings.getFile().exists()) {
        try {
            FIRST_START = true;
            OSMCBSettings.save();
        } catch (Exception e) {
            log.error("Error while creating settings.xml: " + e.getMessage(), e);
            String[] options = { "Exit", "Show error report" };
            int a = JOptionPane.showOptionDialog(null,
                    "Could not create file settings.xml - program will exit.", "Error", 0,
                    JOptionPane.ERROR_MESSAGE, null, options, options[0]);
            if (a == 1)
                GUIExceptionHandler.showExceptionDialog(e);
            System.exit(1);
        }
    }
}

From source file:osmcd.program.EnvironmentSetup.java

/**
 * Note: This method has be be called before {@link Settings#loadOrQuit()}. Therefore no localization is available at this point.
 */// www . ja v  a  2s .  c om
public static void checkFileSetup() {
    checkDirectory(DirectoryManager.userSettingsDir, "user settings", true);
    checkDirectory(DirectoryManager.atlasProfilesDir, "atlas profile", true);
    checkDirectory(DirectoryManager.tileStoreDir, "tile store", true);
    checkDirectory(DirectoryManager.tempDir, "temporary atlas download", true);
    if (!Settings.FILE.exists()) {
        try {
            FIRST_START = true;
            Settings.save();
        } catch (Exception e) {
            log.error("Error while creating settings.xml: " + e.getMessage(), e);
            String[] options = { "Exit", "Show error report" };
            int a = JOptionPane.showOptionDialog(null,
                    "Could not create file settings.xml - program will exit.", "Error", 0,
                    JOptionPane.ERROR_MESSAGE, null, options, options[0]);
            if (a == 1)
                GUIExceptionHandler.showExceptionDialog(e);
            System.exit(1);
        }
    }
}

From source file:output.ExcelM3Upgrad.java

public boolean save() {
    dialStatus();// w w  w  .j av  a 2 s .  c  o  m
    try {
        if (workbook instanceof HSSFWorkbook) {
            if (!filepath.endsWith("xls")) {
                filepath += ".xls";
            }
        } else if (workbook instanceof XSSFWorkbook) {
            if (!filepath.endsWith("xlsx")) {
                filepath += ".xlsx";
            }
        }
        busyDial.setText("Sauvegarde du fichier " + filepath);
        FileOutputStream out = new FileOutputStream(new File(filepath));
        workbook.write(out);
        out.close();
        if (endFile) {
            Object[] options = { i18n.Language.getLabel(140), i18n.Language.getLabel(23),
                    i18n.Language.getLabel(130) };
            int n = JOptionPane.showOptionDialog(busyDial, i18n.Language.getLabel(213), "Excel",
                    JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);

            if (n == 0) {
                busyDial.setText(i18n.Language.getLabel(214) + "...");
                Desktop dt = Desktop.getDesktop();
                dt.open(new File(filepath));
            } else if (n == 1) {
                try {
                    busyDial.setText(i18n.Language.getLabel(215) + "...");
                    GmailTLS mail = new GmailTLS();
                    Message msg = mail.writeMail("j.chaut@3kles-consulting.com", "M3Upgrader",
                            "Rsultat de M3Upgrader");
                    msg = mail.addAttachment(msg, new File(filepath));
                    busyDial.setText(i18n.Language.getLabel(216) + "...");
                    mail.sendMail(msg);
                } catch (MessagingException ex) {
                    Ressource.logger.error(ex.getLocalizedMessage(), ex);
                }
            }
            in.close();
        }
    } catch (IOException e) {
        error(e.getMessage());
        return false;
    }
    return true;
}

From source file:pcgen.gui2.PCGenFrame.java

public boolean closeAllCharacters() {
    final int CLOSE_OPT_CHOOSE = 2;
    ListFacade<CharacterFacade> characters = CharacterManager.getCharacters();
    if (characters.isEmpty()) {
        return true;
    }/*  www  .jav a2 s . c  o m*/
    int saveAllChoice = CLOSE_OPT_CHOOSE;

    List<CharacterFacade> characterList = new ArrayList<>();
    List<CharacterFacade> unsavedPCs = new ArrayList<>();
    for (CharacterFacade characterFacade : characters) {
        if (characterFacade.isDirty()) {
            unsavedPCs.add(characterFacade);
        } else {
            characterList.add(characterFacade);
        }
    }
    if (unsavedPCs.size() > 1) {
        Object[] options = new Object[] { LanguageBundle.getString("in_closeOptSaveAll"), //$NON-NLS-1$
                LanguageBundle.getString("in_closeOptSaveNone"), //$NON-NLS-1$
                LanguageBundle.getString("in_closeOptChoose"), //$NON-NLS-1$
                LanguageBundle.getString("in_cancel") //$NON-NLS-1$
        };
        saveAllChoice = JOptionPane.showOptionDialog(this, LanguageBundle.getString("in_closeOptSaveTitle"), //$NON-NLS-1$
                Constants.APPLICATION_NAME, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
                null, options, options[0]);
    }
    if (saveAllChoice == 3) {
        // Cancel
        return false;
    }
    if (saveAllChoice == 1) {
        // Save none
        CharacterManager.removeAllCharacters();
        return true;
    }

    for (CharacterFacade character : unsavedPCs) {
        int saveSingleChoice = JOptionPane.YES_OPTION;

        if (saveAllChoice == CLOSE_OPT_CHOOSE) {
            saveSingleChoice = JOptionPane.showConfirmDialog(this,
                    LanguageBundle.getFormattedString("in_savePcChoice", character //$NON-NLS-1$
                            .getNameRef().get()),
                    Constants.APPLICATION_NAME, JOptionPane.YES_NO_CANCEL_OPTION);
        }

        if (saveSingleChoice == JOptionPane.YES_OPTION) {//If you get here then the user either selected "Yes to All" or "Yes"
            if (saveCharacter(character)) {
                characterList.add(character);
            }
        } else if (saveSingleChoice == JOptionPane.NO_OPTION) {
            characterList.add(character);
        } else if (saveSingleChoice == JOptionPane.CANCEL_OPTION) {
            return false;
        }
    }

    for (CharacterFacade character : characterList) {
        CharacterManager.removeCharacter(character);
    }
    return characters.isEmpty();
}

From source file:pcgen.gui2.PCGenFrame.java

/**
 * Loads a character from a file. Any sources that are required for
 * this character are loaded first, then the character is loaded
 * from the file and a tab is opened for it.
 * @param pcgFile a file specifying the character to be loaded
 *///from ww  w .j  a va  2 s  .c  o m
public void loadCharacterFromFile(final File pcgFile) {
    if (!PCGFile.isPCGenCharacterFile(pcgFile)) {
        JOptionPane.showMessageDialog(this, LanguageBundle.getFormattedString("in_loadPcInvalid", pcgFile), //$NON-NLS-1$
                LanguageBundle.getString("in_loadPcFailTtile"), //$NON-NLS-1$
                JOptionPane.ERROR_MESSAGE);
        return;
    }
    if (!pcgFile.canRead()) {
        JOptionPane.showMessageDialog(this, LanguageBundle.getFormattedString("in_loadPcNoRead", pcgFile), //$NON-NLS-1$
                LanguageBundle.getString("in_loadPcFailTtile"), //$NON-NLS-1$
                JOptionPane.ERROR_MESSAGE);
        return;
    }

    SourceSelectionFacade sources = CharacterManager.getRequiredSourcesForCharacter(pcgFile, this);
    if (sources == null) {
        JOptionPane.showMessageDialog(this, LanguageBundle.getFormattedString("in_loadPcNoSources", pcgFile), //$NON-NLS-1$
                LanguageBundle.getString("in_loadPcFailTtile"), //$NON-NLS-1$
                JOptionPane.ERROR_MESSAGE);
    } else if (!sources.getCampaigns().isEmpty()) {
        // Check if the user has asked that sources not be loaded with the character
        boolean dontLoadSources = currentSourceSelection.get() != null && !PCGenSettings.OPTIONS_CONTEXT
                .initBoolean(PCGenSettings.OPTION_AUTOLOAD_SOURCES_WITH_PC, true);
        boolean sourcesSame = checkSourceEquality(sources, currentSourceSelection.get());
        boolean gameModesSame = checkGameModeEquality(sources, currentSourceSelection.get());
        if (!dontLoadSources && !sourcesSame && gameModesSame) {
            Object[] btnNames = new Object[] { LanguageBundle.getString("in_loadPcDiffSourcesLoaded"),
                    LanguageBundle.getString("in_loadPcDiffSourcesCharacter"),
                    LanguageBundle.getString("in_cancel") };
            int choice = JOptionPane.showOptionDialog(this,
                    LanguageBundle.getFormattedString("in_loadPcDiffSources",
                            getFormattedCampaigns(currentSourceSelection.get()),
                            getFormattedCampaigns(sources)),
                    LanguageBundle.getString("in_loadPcSourcesLoadTitle"), JOptionPane.YES_NO_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE, null, btnNames, null);
            if (choice == JOptionPane.CANCEL_OPTION) {
                return;
            }
            if (choice == JOptionPane.YES_OPTION) {
                openCharacter(pcgFile, currentDataSetRef.get());
                return;
            }
        }

        if (dontLoadSources) {
            if (!checkSourceEquality(sources, currentSourceSelection.get())) {
                Logging.log(Logging.WARNING, "Loading character with different sources. Character: " + sources
                        + " current: " + currentSourceSelection.get());
            }
            openCharacter(pcgFile, currentDataSetRef.get());
        } else if (loadSourceSelection(sources)) {
            loadSourcesThenCharacter(pcgFile);
        } else {
            JOptionPane.showMessageDialog(this, LanguageBundle.getString("in_loadPcIncompatSource"), //$NON-NLS-1$
                    LanguageBundle.getString("in_loadPcFailTtile"), //$NON-NLS-1$
                    JOptionPane.ERROR_MESSAGE);
        }
    } else if (currentDataSetRef.get() != null) {
        if (showWarningConfirm(Constants.APPLICATION_NAME,
                LanguageBundle.getFormattedString("in_loadPcSourcesLoadQuery", //$NON-NLS-1$
                        pcgFile))) {
            openCharacter(pcgFile, currentDataSetRef.get());
        }
    } else {
        // No character sources and no sources loaded.
        JOptionPane.showMessageDialog(this, LanguageBundle.getFormattedString("in_loadPcNoSources", pcgFile), //$NON-NLS-1$
                LanguageBundle.getString("in_loadPcFailTtile"), //$NON-NLS-1$
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:pl.otros.logview.exceptionshandler.ShowErrorDialogExceptionHandler.java

@Override
protected void uncaughtExceptionInSwingEDT(Thread thread, Throwable throwable) {
    String stackTraceAsString = Throwables.getStackTraceAsString(throwable);
    if (caughtStackTraces.contains(stackTraceAsString)) {
        LOGGER.info("Not sending the same error report twice");
        return;/*from  w ww  .  j  ava  2 s. co  m*/
    }
    caughtStackTraces.add(stackTraceAsString);
    JPanel message = new JPanel(new BorderLayout());
    message.add(new JLabel("Error in thread " + thread.getName()), BorderLayout.NORTH);

    String stackTrace = getStackTrace(throwable);
    JTextArea textArea = new JTextArea(10, 70);
    textArea.setText(stackTrace);
    textArea.setCaretPosition(0);
    message.add(new JScrollPane(textArea));

    JOptionPane.showMessageDialog(null, message, "Error", JOptionPane.ERROR_MESSAGE);

    Map<String, String> errorReportData = generateReportData(thread, throwable, otrosApplication);
    JComponent jComponent = createDialogView();
    String[] options = { "Send", "Do not send" };
    int sendReport = JOptionPane.showOptionDialog(otrosApplication.getApplicationJFrame(), jComponent,
            "Send error report confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
            Icons.MEGAPHONE_24, options, options[0]);
    errorReportData.put("USER:email", emailTextField.getText());
    errorReportData.put("USER:comment", commentTextArea.getText());

    if (sendReport == JOptionPane.YES_OPTION) {
        DataConfiguration c = otrosApplication.getConfiguration();
        c.setProperty(ConfKeys.HTTP_PROXY_USE, checkBoxUseProxy.isSelected());
        c.setProperty(ConfKeys.HTTP_PROXY_HOST, proxyTf.getText());
        c.setProperty(ConfKeys.HTTP_PROXY_PORT, proxyPortModel.getNumber().intValue());
        c.setProperty(ConfKeys.HTTP_PROXY_USER, proxyUser.getText());
        sendReportInNewBackground(errorReportData);
    } else {
        LOGGER.info("Not sending error report");
    }

    logErrorReport(errorReportData);

}