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:com.t3.client.TabletopTool.java

/**
 * This method is specific to deleting a token, but it can be used as a
 * basis for any other method which wants to be turned off via a property.
 * //from w ww .j  av  a2s.c om
 * @return true if the token should be deleted.
 */
public static boolean confirmTokenDelete() {
    if (!AppPreferences.getTokensWarnWhenDeleted()) {
        return true;
    }

    String msg = I18N.getText("msg.confirm.deleteToken");
    log.debug(msg);
    Object[] options = { I18N.getText("msg.title.messageDialog.yes"),
            I18N.getText("msg.title.messageDialog.no"), I18N.getText("msg.title.messageDialog.dontAskAgain") };
    String title = I18N.getText("msg.title.messageDialogConfirm");
    int val = JOptionPane.showOptionDialog(clientFrame, msg, title, JOptionPane.NO_OPTION,
            JOptionPane.WARNING_MESSAGE, null, options, options[0]);

    // "Yes, don't show again" Button
    if (val == 2) {
        showInformation("msg.confirm.deleteToken.removed");
        AppPreferences.setTokensWarnWhenDeleted(false);
    }
    // Any version of 'Yes'...
    if (val == JOptionPane.YES_OPTION || val == 2) {
        return true;
    }
    // Assume 'No' response
    return false;
}

From source file:be.ugent.maf.cellmissy.gui.controller.analysis.singlecell.AngleDirectController.java

/**
 * @param pdfFile/*from   ww  w . jav  a 2s.c  om*/
 */
private void tryToCreateFile(File pdfFile, JFreeChart chart) {
    try {
        boolean success = pdfFile.createNewFile();
        if (success) {
            singleCellPreProcessingController.showMessage("Chart saved to file!", "chart saved OK",
                    JOptionPane.INFORMATION_MESSAGE);
        } else {
            Object[] options = { "Yes", "No", "Cancel" };
            int showOptionDialog = JOptionPane.showOptionDialog(null,
                    "File already exists. Do you want to replace it?", "", JOptionPane.YES_NO_OPTION,
                    JOptionPane.WARNING_MESSAGE, null, options, options[2]);
            // if YES, user wants to delete existing file and replace it
            if (showOptionDialog == 0) {
                boolean delete = pdfFile.delete();
                if (!delete) {
                    return;
                }
                // if NO, returns already existing file
            } else if (showOptionDialog == 1) {
                return;
            }
        }
    } catch (IOException ex) {
        singleCellPreProcessingController.showMessage("Unexpected error: " + ex.getMessage() + ".",
                "Unexpected error", JOptionPane.ERROR_MESSAGE);
        return;
    }
    try (FileOutputStream fileOutputStream = new FileOutputStream(pdfFile)) {
        // actually create PDF file
        createPdfFile(fileOutputStream, chart);
    } catch (IOException ex) {
        singleCellPreProcessingController.showMessage("Unexpected error: " + ex.getMessage() + ".",
                "Unexpected error", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:lu.fisch.unimozer.Diagram.java

public void doAutoSave() {
    //if (saveTimer.isRunning()) saveTimer.stop();
    if (hasChangedAutoSave == true) {
        // has the project allready been saved once?
        //if(directoryName==null)
        //{/*from   w  w  w  .  j  a  v  a 2  s .com*/
        // no, so ask to save it right now
        //custom title, warning icon
        Object[] options = { "Yes", "No" };
        int n = JOptionPane.showOptionDialog(frame,
                "You didn't save your project yet!\n" + "Do you want to save it right now?", "Auto save",
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
        if (n == 0) {
            this.saveUnimozer();
            hasChangedAutoSave = false;
        }
        //}
        /*            else
                    {
        // yes, so go ahead an create a backup
        createBackup();
        hasChangedAutoSave=false;
                    }
                    saveTimer.start();
        */
    } else if (hasChanged) {
        Object[] options = { "Yes", "No" };
        int n = JOptionPane.showOptionDialog(frame,
                "You didn't save your project for at least 10 minutes!\n" + "Do you want to save it right now?",
                "Auto save", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,
                options[0]);
        if (n == 0) {
            this.saveUnimozer();
        }
    }

}

From source file:net.rptools.maptool.client.MapTool.java

public static boolean confirmDrawDelete() {
    if (!AppPreferences.getDrawWarnWhenDeleted()) {
        return true;
    }//  w w  w .ja  v a 2  s  .  c  o m

    String msg = I18N.getText("msg.confirm.deleteDraw");
    log.debug(msg);
    Object[] options = { I18N.getText("msg.title.messageDialog.yes"),
            I18N.getText("msg.title.messageDialog.no"), I18N.getText("msg.title.messageDialog.dontAskAgain") };
    String title = I18N.getText("msg.title.messageDialogConfirm");
    int val = JOptionPane.showOptionDialog(clientFrame, msg, title, JOptionPane.NO_OPTION,
            JOptionPane.WARNING_MESSAGE, null, options, options[0]);

    // "Yes, don't show again" Button
    if (val == 2) {
        showInformation("msg.confirm.deleteDraw.removed");
        AppPreferences.setDrawWarnWhenDeleted(false);
    }
    // Any version of 'Yes'...
    if (val == JOptionPane.YES_OPTION || val == 2) {
        return true;
    }
    // Assume 'No' response
    return false;
}

From source file:com.sec.ose.osi.ui.frm.main.report.JPanExportReport.java

private JButton getJButtonOK() {
    if (jButtonOK == null) {
        jButtonOK = new JButton();
        jButtonOK.setText("   OK   ");
        jButtonOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {

                String dirPath = jTextFieldReportLocation.getText();
                File dir = new File(dirPath);
                if (dir.exists() == false) {
                    int choice = JOptionPane.showOptionDialog(null,
                            "\"" + dir + "\" is not existed folder. Do you want to create it now?", "Alarm",
                            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
                    if (choice == JOptionPane.NO_OPTION) {
                        return;
                    }//from   w w w.ja v a  2s. c  o m
                    dir.mkdirs();
                }

                if (getJRadioButtonIdentify().isSelected()) {
                    mEventHandler.handle(EventHandler.BTN_OK_IDENTIFY);
                } else if (getJRadioButtonSPDX().isSelected()) {
                    mEventHandler.handle(EventHandler.BTN_OK_SPDX);
                } else if (getJRadioButtonBoth().isSelected()) {
                    mEventHandler.handle(EventHandler.BTN_OK_BOTH);
                }
            }
        });
    }
    return jButtonOK;
}

From source file:edu.ku.brc.specify.dbsupport.TaskSemaphoreMgr.java

/**
 * Locks the semaphore./*w  w w. j a v a 2  s  . co m*/
 * @param title The human (localized) title of the task 
 * @param name the unique name
 * @param context
 * @param scope the scope of the lock
 * @param allViewMode allows it to ask the user about 'View Only'
 * @return
 */
public static USER_ACTION lock(final String title, final String name, final String context, final SCOPE scope,
        final boolean allViewMode, final TaskSemaphoreMgrCallerIFace caller, final boolean checkUsage) {
    DataProviderSessionIFace session = null;
    try {
        session = DataProviderFactory.getInstance().createSession();

        int count = 0;
        do {

            SpTaskSemaphore semaphore = null;
            try {
                semaphore = setLock(session, name, context, scope, true, false, checkUsage);

            } catch (StaleObjectException ex) {
                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(TaskSemaphoreMgr.class, ex);
                semaphore = null;
            }

            if (semaphore == null || previouslyLocked) {
                if (caller != null) {
                    return caller.resolveConflict(semaphore, previouslyLocked, prevLockedBy);
                }

                if (semaphore == null) {
                    String msg = UIRegistry.getLocalizedMessage("SpTaskSemaphore.IN_USE", title);//$NON-NLS-1$
                    Object[] options = { getResourceString("SpTaskSemaphore.TRYAGAIN"), //$NON-NLS-1$
                            getResourceString("CANCEL") //$NON-NLS-1$
                    };
                    int userChoice = JOptionPane.showOptionDialog(UIRegistry.getTopWindow(), msg,
                            getResourceString("SpTaskSemaphore.IN_USE_TITLE"), //$NON-NLS-1$
                            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
                    if (userChoice == JOptionPane.NO_OPTION) {
                        return USER_ACTION.Cancel;
                    }

                } else {
                    // Check to see if we have the same user on the same machine.
                    SpecifyUser user = AppContextMgr.getInstance().getClassObject(SpecifyUser.class);
                    String currMachineName = InetAddress.getLocalHost().toString();
                    String dbMachineName = semaphore.getMachineName();

                    //System.err.println("["+dbMachineName+"]["+currMachineName+"]["+user.getId()+"]["+semaphore.getOwner().getId()+"]");
                    if (StringUtils.isNotEmpty(dbMachineName) && StringUtils.isNotEmpty(currMachineName)
                            && currMachineName.equals(dbMachineName) && semaphore.getOwner() != null
                            && user != null && user.getId().equals(semaphore.getOwner().getId())) {
                        if (allViewMode) {
                            int options = JOptionPane.YES_NO_OPTION;
                            Object[] optionLabels = new String[] {
                                    getResourceString("SpTaskSemaphore.VIEWMODE"), //$NON-NLS-1$
                                    getResourceString("CANCEL")//$NON-NLS-1$
                            };
                            int userChoice = JOptionPane.showOptionDialog(UIRegistry.getTopWindow(),
                                    getLocalizedMessage("SpTaskSemaphore.IN_USE_BY_YOU", title),
                                    getResourceString("SpTaskSemaphore.IN_USE_TITLE"), //$NON-NLS-1$
                                    options, JOptionPane.QUESTION_MESSAGE, null, optionLabels, 0);

                            return userChoice == JOptionPane.NO_OPTION ? USER_ACTION.Cancel
                                    : USER_ACTION.ViewMode; // CHECKED
                        }

                        int options = JOptionPane.OK_OPTION;
                        Object[] optionLabels = new String[] { getResourceString("OK")//$NON-NLS-1$
                        };
                        JOptionPane.showOptionDialog(UIRegistry.getTopWindow(),
                                getLocalizedMessage("SpTaskSemaphore.IN_USE_BY_YOU", title),
                                getResourceString("SpTaskSemaphore.IN_USE_TITLE"), //$NON-NLS-1$
                                options, JOptionPane.QUESTION_MESSAGE, null, optionLabels, 0);

                        return USER_ACTION.Cancel;
                    }

                    String userStr = prevLockedBy != null ? prevLockedBy
                            : semaphore.getOwner().getIdentityTitle();
                    String msgKey = allViewMode ? "SpTaskSemaphore.IN_USE_OV" : "SpTaskSemaphore.IN_USE";
                    String msg = UIRegistry.getLocalizedMessage(msgKey, title, userStr,
                            semaphore.getLockedTime() != null ? semaphore.getLockedTime().toString() : "");

                    int options;
                    int defBtn;
                    Object[] optionLabels;
                    if (allViewMode) {
                        defBtn = 2;
                        options = JOptionPane.YES_NO_CANCEL_OPTION;
                        optionLabels = new String[] { getResourceString("SpTaskSemaphore.VIEWMODE"), //$NON-NLS-1$
                                getResourceString("SpTaskSemaphore.TRYAGAIN"), //$NON-NLS-1$
                                getResourceString("CANCEL")//$NON-NLS-1$
                        };
                    } else {
                        defBtn = 0;
                        options = JOptionPane.YES_NO_OPTION;
                        optionLabels = new String[] { getResourceString("SpTaskSemaphore.TRYAGAIN"), //$NON-NLS-1$
                                getResourceString("CANCEL"), //$NON-NLS-1$
                        };
                    }

                    int userChoice = JOptionPane.showOptionDialog(UIRegistry.getTopWindow(), msg,
                            getResourceString("SpTaskSemaphore.IN_USE_TITLE"), //$NON-NLS-1$
                            options, JOptionPane.QUESTION_MESSAGE, null, optionLabels, defBtn);
                    if (userChoice == JOptionPane.YES_OPTION) {
                        if (options == JOptionPane.YES_NO_CANCEL_OPTION) {
                            return USER_ACTION.ViewMode; // CHECKED
                        }
                        // this means try again

                    } else if (userChoice == JOptionPane.NO_OPTION) {
                        if (options == JOptionPane.YES_NO_OPTION) {
                            return USER_ACTION.Cancel;
                        }
                        // CHECKED

                    } else if (userChoice == JOptionPane.CANCEL_OPTION) {
                        return USER_ACTION.Cancel; // CHECKED
                    }
                }
            } else {
                return USER_ACTION.OK;
            }

            count++;

        } while (true);

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(TaskSemaphoreMgr.class, ex);
        ex.printStackTrace();
        //log.error(ex);

    } finally {
        if (session != null) {
            session.close();
        }
    }
    return USER_ACTION.Error;
}

From source file:be.ac.ua.comp.scarletnebula.gui.windows.GUI.java

public void terminateSelectedServers() {
    final Collection<Server> servers = serverList.getSelectedServers();

    if (servers.isEmpty()) {
        return;/*from   www . j a v  a2  s .  com*/
    }

    final String deleteMessage = "You are about to terminate " + servers.size() + " server(s). \n"
            + "Terminating a server will permanently destroy the server. This operation cannot be undone.\n\n"
            + "Do you wish to proceed?";

    final String deleteTitle = "Terminate " + servers.size() + " server(s)";
    final String buttonString = deleteTitle;
    final int result = JOptionPane.showOptionDialog(this, deleteMessage, deleteTitle,
            JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null,
            Arrays.asList(buttonString, "Cancel").toArray(), "Cancel");

    if (result != JOptionPane.OK_OPTION) {
        return;
    }

    (new SwingWorkerWithThrobber<Exception, Object>(
            newThrobber("Terminating server" + ((servers.size() > 1) ? "s" : ""))) {
        @Override
        protected Exception doInBackground() throws Exception {
            for (final Server server : servers) {
                try {
                    server.terminate();
                    server.refreshUntilServerHasState(VmState.TERMINATED);
                } catch (final Exception e) {
                    return e;
                }
            }
            return null;
        }

        @Override
        public void done() {
            try {
                final Exception result = get();

                if (result != null) {
                    log.error(result);
                    error(result);
                }
            } catch (final Exception ignore) {
            }
        }
    }).execute();

}

From source file:com.holycityaudio.SpinCAD.SpinCADFile.java

public void fileSaveAsm(SpinCADPatch patch) {
    // Create a file chooser
    String savedPath = prefs.get("MRUSpnFolder", "");

    final JFileChooser fc = new JFileChooser(savedPath);
    // In response to a button click:
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Spin ASM Files", "spn");
    fc.setFileFilter(filter);/*from  ww w .  j av  a 2 s . c o  m*/
    // XXX DEBUG
    fc.showSaveDialog(new JFrame());
    File fileToBeSaved = fc.getSelectedFile();

    if (!fc.getSelectedFile().getAbsolutePath().endsWith(".spn")) {
        fileToBeSaved = new File(fc.getSelectedFile() + ".spn");
    }
    int n = JOptionPane.YES_OPTION;
    if (fileToBeSaved.exists()) {
        JFrame frame1 = new JFrame();
        n = JOptionPane.showConfirmDialog(frame1, "Would you like to overwrite it?", "File already exists!",
                JOptionPane.YES_NO_OPTION);
    }
    if (n == JOptionPane.YES_OPTION) {
        String filePath = fileToBeSaved.getPath();
        fileToBeSaved.delete();

        try {
            fileSaveAsm(patch, filePath);
        } catch (IOException e) {
            JOptionPane.showOptionDialog(null, "File save error!", "Error", JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE, null, null, null);
            e.printStackTrace();
        }
        saveMRUSpnFolder(filePath);
    }
}

From source file:edu.ku.brc.af.prefs.PreferencesDlg.java

@Override
public boolean closePrefs() {
    if (okBtn.isEnabled()) {
        Object[] options = { getResourceString("PrefsDlg.SAVE_PREFS"), //$NON-NLS-1$
                getResourceString("PrefsDlg.DONT_SAVE_PREFS"), //$NON-NLS-1$
                getResourceString("CANCEL") //$NON-NLS-1$
        };/*from w  w w  .  j  a  va  2s. c om*/
        int userChoice = JOptionPane.showOptionDialog(UIRegistry.getTopWindow(),
                getResourceString("PrefsDlg.MSG"), //$NON-NLS-1$
                getResourceString("PREFERENCES"), //$NON-NLS-1$
                JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
        if (userChoice == JOptionPane.YES_OPTION) {
            okButtonPressed();

        } else if (userChoice == JOptionPane.NO_OPTION) {
            cancelButtonPressed();
        } else {
            return false;
        }
    } else {
        cancelButtonPressed();
    }
    return true;
}

From source file:net.pms.newgui.LanguageSelection.java

private JComponent buildComponent() {
    // UIManager manages to get the background color wrong for text
    // components on OS X, so we apply the color manually
    Color backgroundColor = UIManager.getColor("Panel.background");
    rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.PAGE_AXIS));

    // It needs to be something in the title text, or the size calculation for the border will be wrong.
    selectionPanelBorder.setTitle(" ");
    selectionPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5),
            BorderFactory.createCompoundBorder(selectionPanelBorder,
                    BorderFactory.createEmptyBorder(10, 5, 10, 5))));
    selectionPanel.setLayout(new BoxLayout(selectionPanel, BoxLayout.PAGE_AXIS));
    descriptionText.setEditable(false);// w  w  w .  jav a  2  s.  c o  m
    descriptionText.setBackground(backgroundColor);
    descriptionText.setFocusable(false);
    descriptionText.setLineWrap(true);
    descriptionText.setWrapStyleWord(true);
    descriptionText.setBorder(BorderFactory.createEmptyBorder(5, 15, 10, 15));
    selectionPanel.add(descriptionText);

    jLanguage = new JComboBox<>(keyedModel);
    jLanguage.setEditable(false);
    jLanguage.setPreferredSize(new Dimension(50, jLanguage.getPreferredSize().height));
    jLanguage.addActionListener(new LanguageComboBoxActionListener());
    languagePanel.setLayout(new BoxLayout(languagePanel, BoxLayout.PAGE_AXIS));
    languagePanel.setBorder(BorderFactory.createEmptyBorder(5, 15, 5, 15));
    languagePanel.add(jLanguage);
    selectionPanel.add(languagePanel);

    warningText.setEditable(false);
    warningText.setFocusable(false);
    warningText.setBackground(backgroundColor);
    warningText.setFont(warningText.getFont().deriveFont(Font.BOLD));
    warningText.setLineWrap(true);
    warningText.setWrapStyleWord(true);
    warningText.setBorder(BorderFactory.createEmptyBorder(5, 15, 0, 15));
    selectionPanel.add(warningText);

    // It needs to be something in the title text, or the size calculation for the border will be wrong.
    infoTextBorder.setTitle(" ");
    infoText.setBorder(
            BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5), BorderFactory
                    .createCompoundBorder(infoTextBorder, BorderFactory.createEmptyBorder(15, 20, 20, 20))));
    infoText.setEditable(false);
    infoText.setFocusable(false);
    infoText.setBackground(backgroundColor);
    infoText.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);

    // This exercise is to avoid using the default shared StyleSheet with padding
    CustomHTMLEditorKit editorKit = new CustomHTMLEditorKit();
    StyleSheet styleSheet = new StyleSheet();
    styleSheet.addRule("a { color: #0000EE; text-decoration:underline; }");
    editorKit.setStyleSheet(styleSheet);
    infoText.setEditorKit(editorKit);
    infoText.addHyperlinkListener(new HyperlinkListener() {

        @Override
        public void hyperlinkUpdate(HyperlinkEvent e) {
            if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                boolean error = false;
                if (Desktop.isDesktopSupported()) {
                    try {
                        Desktop.getDesktop().browse(new URI(e.getDescription()));
                    } catch (IOException | URISyntaxException ex) {
                        LOGGER.error("Language selection failed to open translation page hyperlink: ",
                                ex.getMessage());
                        LOGGER.trace("", ex);
                        error = true;
                    }
                } else {
                    LOGGER.warn("Desktop is not supported, the clicked translation page link can't be opened");
                    error = true;
                }
                if (error) {
                    JOptionPane.showOptionDialog(dialog,
                            String.format(buildString("LanguageSelection.6", true), PMS.CROWDIN_LINK),
                            buildString("Dialog.Error"), JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE,
                            null, null, null);
                }
            }
        }

    });

    rootPanel.add(selectionPanel);
    rootPanel.add(infoText);

    applyButton.addActionListener(new ApplyButtonActionListener());
    applyButton.setActionCommand("apply");

    selectButton.addActionListener(new SelectButtonActionListener());
    selectButton.setActionCommand("select");

    return rootPanel;

}