Example usage for javax.swing JOptionPane CANCEL_OPTION

List of usage examples for javax.swing JOptionPane CANCEL_OPTION

Introduction

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

Prototype

int CANCEL_OPTION

To view the source code for javax.swing JOptionPane CANCEL_OPTION.

Click Source Link

Document

Return value from class method if CANCEL is chosen.

Usage

From source file:net.sf.profiler4j.console.Console.java

/**
 * /*from w w w  .  j ava 2  s.c om*/
 * @return <code>true</code> if the user has cancelled
 */
private boolean checkUnsavedChanges() {
    if (project.isChanged()) {
        int ret = JOptionPane.showConfirmDialog(mainFrame, "Project has unsaved changes? Save before exit?",
                "Unsaved Changes", JOptionPane.YES_NO_CANCEL_OPTION);
        if (ret == JOptionPane.CANCEL_OPTION) {
            return true;
        } else if (ret == JOptionPane.YES_OPTION) {
            return saveProject(false);
        }
    }
    return false;
}

From source file:net.sf.jabref.gui.exporter.SaveDatabaseAction.java

/**
 * Check whether or not the external database has been modified. If so need to alert the user to accept external updates prior to
 * saving the database. This is necessary to avoid overwriting other users work when using a multiuser database file.
 *
 * @return true if the external database file has been modified and the user must choose to accept the changes and false if no modifications
 * were found or there is no requested protection for the database file.
 *//*  www. j av a 2  s. com*/
private boolean checkExternalModification() {
    // Check for external modifications:
    if (panel.isUpdatedExternally()
            || Globals.getFileUpdateMonitor().hasBeenModified(panel.getFileMonitorHandle())) {
        String[] opts = new String[] { Localization.lang("Review changes"), Localization.lang("Save"),
                Localization.lang("Cancel") };
        int answer = JOptionPane.showOptionDialog(panel.frame(),
                Localization.lang("File has been updated externally. " + "What do you want to do?"),
                Localization.lang("File updated externally"), JOptionPane.YES_NO_CANCEL_OPTION,
                JOptionPane.QUESTION_MESSAGE, null, opts, opts[0]);

        if (answer == JOptionPane.CANCEL_OPTION) {
            canceled = true;
            return true;
        } else if (answer == JOptionPane.YES_OPTION) {
            canceled = true;

            JabRefExecutorService.INSTANCE.execute(() -> {

                if (!FileBasedLock.waitForFileLock(panel.getBibDatabaseContext().getDatabaseFile().toPath(),
                        10)) {
                    // TODO: GUI handling of the situation when the externally modified file keeps being locked.
                    LOGGER.error("File locked, this will be trouble.");
                }

                ChangeScanner scanner = new ChangeScanner(panel.frame(), panel,
                        panel.getBibDatabaseContext().getDatabaseFile());
                JabRefExecutorService.INSTANCE.executeWithLowPriorityInOwnThreadAndWait(scanner);
                if (scanner.changesFound()) {
                    scanner.displayResult(resolved -> {
                        if (resolved) {
                            panel.setUpdatedExternally(false);
                            SwingUtilities.invokeLater(() -> panel.getSidePaneManager().hide("fileUpdate"));
                        } else {
                            canceled = true;
                        }
                    });
                }
            });

            return true;
        } else { // User indicated to store anyway.
            if (panel.getBibDatabaseContext().getMetaData().isProtected()) {
                JOptionPane.showMessageDialog(frame, Localization
                        .lang("Database is protected. Cannot save until external changes have been reviewed."),
                        Localization.lang("Protected database"), JOptionPane.ERROR_MESSAGE);
                canceled = true;
            } else {
                panel.setUpdatedExternally(false);
                panel.getSidePaneManager().hide("fileUpdate");
            }
        }
    }

    // Return false as either no external database file modifications have been found or overwrite is requested any way
    return false;
}

From source file:gui.QTLResultsPanel.java

void saveTXT() {
    JFileChooser fc = new JFileChooser();
    fc.setCurrentDirectory(new File(Prefs.gui_dir));
    fc.setDialogTitle("Save QTL Results");

    while (fc.showSaveDialog(MsgBox.frm) == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();

        // Make sure it has an appropriate extension
        if (!file.exists()) {
            if (file.getName().indexOf(".") == -1) {
                file = new File(file.getPath() + ".csv");
            }/*from  w  w  w.j a v  a  2s . c  o  m*/
        }

        // Confirm overwrite
        if (file.exists()) {
            int response = MsgBox.yesnocan(file + " already exists.\nDo " + "you want to replace it?", 1);

            if (response == JOptionPane.NO_OPTION) {
                continue;
            } else if (response == JOptionPane.CANCEL_OPTION || response == JOptionPane.CLOSED_OPTION) {
                return;
            }
        }

        // Otherwise it's ok to save...
        Prefs.gui_dir = "" + fc.getCurrentDirectory();
        saveTXTFile(file);
        return;
    }
}

From source file:ee.ioc.cs.vsle.editor.Editor.java

/**
 * Close application./*  w  w  w  .  ja  va  2 s . co  m*/
 */
public void exitApplication() {
    int confirmed = JOptionPane.showConfirmDialog(this, "Exit Application?", Menu.EXIT,
            JOptionPane.OK_CANCEL_OPTION);
    switch (confirmed) {
    case JOptionPane.OK_OPTION:

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {

                int state = getExtendedState();

                if ((state & MAXIMIZED_BOTH) == MAXIMIZED_BOTH) {
                    // need to remember window's size in normal mode...looks
                    // ugly,
                    // any other ideas how to get normal size while staying
                    // maximized?
                    setExtendedState(NORMAL);
                }

                RuntimeProperties.setSchemeEditorWindowProps(getBounds(), state);

                RuntimeProperties.save();

                System.exit(0);
            }
        });

        break;
    case JOptionPane.CANCEL_OPTION:
        break;
    }
}

From source file:edu.ku.brc.helpers.EMailHelper.java

/**
 * Asks for a username and password./* w ww.j a v  a2 s .  c o m*/
 * @param topframe the parent frame
 * @return the list of user[index 1] and password[index 2], or 'null' if cancel was pressed
 */
public static ArrayList<String> askForUserAndPassword(final Frame topframe) {
    ArrayList<String> userAndPass = new ArrayList<String>();
    //get remote prefs
    AppPreferences remotePrefs = AppPreferences.getRemote();
    //get remote password
    String remoteUsername = remotePrefs.get("settings.email.username", null); //$NON-NLS-1$

    PanelBuilder builder = new PanelBuilder(new FormLayout("p,2px,p", "p,2px,p,2px,p")); //$NON-NLS-1$ //$NON-NLS-2$
    CellConstraints cc = new CellConstraints();
    JLabel plabel = createI18NFormLabel("EMailHelper.PASSWORD"); //$NON-NLS-1$ //$NON-NLS-2$
    JLabel ulabel = createI18NFormLabel("EMailHelper.USERNAME"); //$NON-NLS-1$ //$NON-NLS-2$
    JPasswordField passField = createPasswordField(25);
    JTextField userField = createTextField(remoteUsername, 25);
    JCheckBox savePassword = createCheckBox(getResourceString("EMailHelper.SAVE_PASSWORD")); //$NON-NLS-1$

    builder.add(ulabel, cc.xy(1, 1));
    builder.add(userField, cc.xy(3, 1));
    builder.add(plabel, cc.xy(1, 3));
    builder.add(passField, cc.xy(3, 3));
    builder.add(savePassword, cc.xy(3, 5));

    Integer option = JOptionPane.showConfirmDialog(topframe, builder.getPanel(),
            getResourceString("EMailHelper.PASSWORD_TITLE"), JOptionPane.OK_CANCEL_OPTION, //$NON-NLS-1$
            JOptionPane.QUESTION_MESSAGE);

    String passwordText = new String(passField.getPassword());
    String userText = new String(userField.getText());

    if (savePassword.isSelected()) {

        if (StringUtils.isNotEmpty(passwordText)) {
            remotePrefs.put("settings.email.password", Encryption.encrypt(passwordText)); //$NON-NLS-1$
        }
    }

    if (option == JOptionPane.CANCEL_OPTION) {
        return null;
    } //else

    userAndPass.add(0, userText);
    userAndPass.add(1, passwordText);
    return userAndPass;
}

From source file:com.dragoniade.deviantart.favorites.FavoritesDownloader.java

private STATUS downloadFile(Deviation da, String downloadUrl, String filename, boolean reportError,
        YesNoAllDialog matureMoveDialog, YesNoAllDialog overwriteDialog, YesNoAllDialog overwriteNewerDialog,
        YesNoAllDialog deleteEmptyDialog) {

    AtomicBoolean download = new AtomicBoolean(true);
    File art = getFile(da, downloadUrl, filename, download, matureMoveDialog, overwriteDialog,
            overwriteNewerDialog, deleteEmptyDialog);
    if (art == null) {
        return null;
    }/*from w  w w  . j  av  a 2  s  .  com*/

    if (download.get()) {
        File parent = art.getParentFile();
        if (!parent.exists()) {
            if (!parent.mkdirs()) {
                showMessageDialog(owner, "Unable to create '" + parent.getPath() + "'.", "Error",
                        JOptionPane.ERROR_MESSAGE);
                return null;
            }
        }

        GetMethod method = new GetMethod(downloadUrl);
        try {
            int sc = -1;
            do {
                sc = client.executeMethod(method);
                requestCount++;
                if (sc != 200) {
                    if (sc == 404 || sc == 403) {
                        method.releaseConnection();
                        return STATUS.NOTFOUND;
                    } else {
                        LoggableException ex = new LoggableException(method.getResponseBodyAsString());
                        Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(),
                                ex);

                        int res = showConfirmDialog(owner,
                                "An error has occured when contacting deviantART : error " + sc
                                        + ". Try again?",
                                "Continue?", JOptionPane.YES_NO_CANCEL_OPTION);
                        if (res == JOptionPane.NO_OPTION) {
                            String text = "<br/><a style=\"color:red;\" href=\"" + da.getUrl() + "\">"
                                    + downloadUrl + " has an error" + "</a>";
                            setPaneText(text);
                            method.releaseConnection();
                            progress.incremTotal();
                            return STATUS.SKIP;
                        }
                        if (res == JOptionPane.CANCEL_OPTION) {
                            return null;
                        }
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                        }
                    }
                }
            } while (sc != 200);

            int length = (int) method.getResponseContentLength();
            int copied = 0;
            progress.setUnitMax(length);
            InputStream is = method.getResponseBodyAsStream();
            File tmpFile = new File(art.getParentFile(), art.getName() + ".tmp");
            FileOutputStream fos = new FileOutputStream(tmpFile, false);
            byte[] buffer = new byte[16184];
            int read = -1;

            while ((read = is.read(buffer)) > 0) {
                fos.write(buffer, 0, read);
                copied += read;
                progress.setUnitValue(copied);

                if (progress.isCancelled()) {
                    is.close();
                    method.releaseConnection();
                    tmpFile.delete();
                    return null;
                }
            }
            fos.close();
            method.releaseConnection();

            if (art.exists()) {
                if (!art.delete()) {
                    showMessageDialog(owner, "Unable to delete '" + art.getPath() + "'.", "Error",
                            JOptionPane.ERROR_MESSAGE);
                    return null;
                }
            }
            if (!tmpFile.renameTo(art)) {
                showMessageDialog(owner,
                        "Unable to rename '" + tmpFile.getPath() + "' to '" + art.getPath() + "'.", "Error",
                        JOptionPane.ERROR_MESSAGE);
                return null;
            }
            art.setLastModified(da.getTimestamp().getTime());
            return STATUS.DOWNLOADED;
        } catch (HttpException e) {
            showMessageDialog(owner, "Error contacting deviantART: " + e.getMessage(), "Error",
                    JOptionPane.ERROR_MESSAGE);
            return null;
        } catch (IOException e) {
            showMessageDialog(owner, "Error contacting deviantART: " + e.getMessage(), "Error",
                    JOptionPane.ERROR_MESSAGE);
            return null;
        }
    } else {
        progress.setText("Skipping file '" + filename + "' from " + da.getArtist());
        return STATUS.SKIP;
    }
}

From source file:com.mirth.connect.client.ui.codetemplate.CodeTemplatePanel.java

public boolean promptSave(boolean force) {
    stopTableEditing();//from   w  ww.ja v  a2 s  .c om
    int option;

    if (force) {
        option = JOptionPane.showConfirmDialog(parent,
                "You must save the code template changes before continuing. Would you like to save now?");
    } else {
        option = JOptionPane.showConfirmDialog(parent, "Would you like to save the code templates?");
    }

    if (option == JOptionPane.YES_OPTION) {
        CodeTemplateLibrarySaveResult updateSummary = doSaveCodeTemplates(false);

        if (updateSummary == null || updateSummary.isOverrideNeeded() || !updateSummary.isLibrariesSuccess()) {
            return false;
        } else {
            for (CodeTemplateUpdateResult result : updateSummary.getCodeTemplateResults().values()) {
                if (!result.isSuccess()) {
                    return false;
                }
            }
        }
    } else if (option == JOptionPane.CANCEL_OPTION || option == JOptionPane.CLOSED_OPTION
            || (option == JOptionPane.NO_OPTION && force)) {
        return false;
    }

    return true;
}

From source file:be.fedict.eid.tsl.tool.TslInternalFrame.java

@Override
public void actionPerformed(ActionEvent event) {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setDialogTitle("Save Signer Certificate");
    int result = fileChooser.showSaveDialog(this);
    if (JFileChooser.APPROVE_OPTION == result) {
        File file = fileChooser.getSelectedFile();
        if (file.exists()) {
            int confirmResult = JOptionPane.showConfirmDialog(this,
                    "File already exists.\n" + file.getAbsolutePath() + "\n" + "Overwrite file?", "Overwrite",
                    JOptionPane.OK_CANCEL_OPTION);
            if (JOptionPane.CANCEL_OPTION == confirmResult) {
                return;
            }//from   ww w .j  a  v a 2 s.c  o m
        }
        try {
            FileUtils.writeByteArrayToFile(file, this.signerCertificate.getEncoded());
        } catch (Exception e) {
            throw new RuntimeException("error writing file: " + e.getMessage(), e);
        }
    }
}

From source file:ffx.ui.KeywordPanel.java

/**
 * Give the user a File Dialog Box so they can select a key file.
 *///from   w w  w .ja va 2s. c  o m
public void keyOpen() {
    if (fileOpen && KeywordComponent.isKeywordModified()) {
        int option = JOptionPane.showConfirmDialog(this, "Save Changes First", "Opening New File",
                JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
        if (option == JOptionPane.CANCEL_OPTION) {
            return;
        } else if (option == JOptionPane.YES_OPTION) {
            keySave(currentKeyFile);
        }
        keyClear();
    }
    JFileChooser d = MainPanel.resetFileChooser();
    if (currentSystem != null) {
        File cwd = currentSystem.getFile();
        if (cwd != null && cwd.getParentFile() != null) {
            d.setCurrentDirectory(cwd.getParentFile());
        }
    }
    d.setAcceptAllFileFilterUsed(false);
    d.setFileFilter(MainPanel.keyFileFilter);
    d.setDialogTitle("Open KEY File");
    int result = d.showOpenDialog(this);
    if (result == JFileChooser.APPROVE_OPTION) {
        File newKeyFile = d.getSelectedFile();
        if (newKeyFile != null && newKeyFile.exists() && newKeyFile.canRead()) {
            keyOpen(newKeyFile);
        }
    }
}

From source file:ca.sqlpower.architect.swingui.enterprise.SecurityPanel.java

private boolean promptForUnsavedChanges() {
    if (currentGroupOrUserEditPanel != null && (currentGroupOrUserEditPanel.hasUnsavedChanges())) {

        int option = JOptionPane.showConfirmDialog(getPanel(),
                "You have not saved all of your changes,\n" + "do you want to save them now?", "",
                JOptionPane.INFORMATION_MESSAGE);

        if (option == JOptionPane.YES_OPTION) {
            currentGroupOrUserEditPanel.applyChanges();
            return true;
        }/*  www  .j a  v  a 2 s.c om*/

        if (option == JOptionPane.NO_OPTION) {
            return true;
        }

        if (option == JOptionPane.CANCEL_OPTION) {
            return false;
        }
    }

    return true;
}