Example usage for javax.swing JOptionPane OK_CANCEL_OPTION

List of usage examples for javax.swing JOptionPane OK_CANCEL_OPTION

Introduction

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

Prototype

int OK_CANCEL_OPTION

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

Click Source Link

Document

Type used for showConfirmDialog.

Usage

From source file:net.sf.jabref.exporter.ExportFormats.java

/**
 * Create an AbstractAction for performing an export operation.
 *
 * @param frame//from ww  w. ja v a 2  s  .com
 *            The JabRefFrame of this JabRef instance.
 * @param selectedOnly
 *            true indicates that only selected entries should be exported,
 *            false indicates that all entries should be exported.
 * @return The action.
 */
public static AbstractAction getExportAction(JabRefFrame frame, boolean selectedOnly) {

    class ExportAction extends MnemonicAwareAction {

        private final JabRefFrame frame;

        private final boolean selectedOnly;

        public ExportAction(JabRefFrame frame, boolean selectedOnly) {
            this.frame = frame;
            this.selectedOnly = selectedOnly;
            putValue(Action.NAME, selectedOnly ? Localization.menuTitle("Export selected entries")
                    : Localization.menuTitle("Export"));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            ExportFormats.initAllExports();
            JFileChooser fc = ExportFormats
                    .createExportFileChooser(Globals.prefs.get(JabRefPreferences.EXPORT_WORKING_DIRECTORY));
            fc.showSaveDialog(frame);
            File file = fc.getSelectedFile();
            if (file == null) {
                return;
            }
            FileFilter ff = fc.getFileFilter();
            if (ff instanceof ExportFileFilter) {

                ExportFileFilter eff = (ExportFileFilter) ff;
                String path = file.getPath();
                if (!path.endsWith(eff.getExtension())) {
                    path = path + eff.getExtension();
                }
                file = new File(path);
                if (file.exists()) {
                    // Warn that the file exists:
                    if (JOptionPane.showConfirmDialog(frame,
                            Localization.lang("'%0' exists. Overwrite file?", file.getName()),
                            Localization.lang("Export"),
                            JOptionPane.OK_CANCEL_OPTION) != JOptionPane.OK_OPTION) {
                        return;
                    }
                }
                final IExportFormat format = eff.getExportFormat();
                List<BibEntry> entries;
                if (selectedOnly) {
                    // Selected entries
                    entries = frame.getCurrentBasePanel().getSelectedEntries();
                } else {
                    // All entries
                    entries = frame.getCurrentBasePanel().getDatabase().getEntries();
                }

                // Set the global variable for this database's file directory before exporting,
                // so formatters can resolve linked files correctly.
                // (This is an ugly hack!)
                Globals.prefs.fileDirForDatabase = frame.getCurrentBasePanel().getBibDatabaseContext()
                        .getFileDirectory();

                // Make sure we remember which filter was used, to set
                // the default for next time:
                Globals.prefs.put(JabRefPreferences.LAST_USED_EXPORT, format.getConsoleName());
                Globals.prefs.put(JabRefPreferences.EXPORT_WORKING_DIRECTORY, file.getParent());

                final File finFile = file;
                final List<BibEntry> finEntries = entries;
                AbstractWorker exportWorker = new AbstractWorker() {

                    String errorMessage;

                    @Override
                    public void run() {
                        try {
                            format.performExport(frame.getCurrentBasePanel().getBibDatabaseContext(),
                                    finFile.getPath(), frame.getCurrentBasePanel().getEncoding(), finEntries);
                        } catch (Exception ex) {
                            LOGGER.warn("Problem exporting", ex);
                            if (ex.getMessage() == null) {
                                errorMessage = ex.toString();
                            } else {
                                errorMessage = ex.getMessage();
                            }
                        }
                    }

                    @Override
                    public void update() {
                        // No error message. Report success:
                        if (errorMessage == null) {
                            frame.output(Localization.lang("%0 export successful", format.getDisplayName()));
                        }
                        // ... or show an error dialog:
                        else {
                            frame.output(Localization.lang("Could not save file.") + " - " + errorMessage);
                            // Need to warn the user that saving failed!
                            JOptionPane.showMessageDialog(frame,
                                    Localization.lang("Could not save file.") + "\n" + errorMessage,
                                    Localization.lang("Save database"), JOptionPane.ERROR_MESSAGE);
                        }
                    }
                };

                // Run the export action in a background thread:
                exportWorker.getWorker().run();
                // Run the update method:
                exportWorker.update();
            }
        }
    }

    return new ExportAction(frame, selectedOnly);
}

From source file:edu.cmu.cs.diamond.pathfind.DjangoAnnotationStore.java

private void login(String loginuri) throws IOException {
    String username = prefs.get("username", "");
    String password = "";

    JLabel label = new JLabel("Please enter your username and password:");
    JTextField jtf = new JTextField(username);
    JPasswordField jpf = new JPasswordField();
    int dialogResult = JOptionPane.showConfirmDialog(null, new Object[] { label, jtf, jpf },
            "Login to PathFind", JOptionPane.OK_CANCEL_OPTION);
    if (dialogResult == JOptionPane.OK_OPTION) {
        username = jtf.getText();/*w ww. j a va  2s  . c om*/
        prefs.put("username", username);
        password = new String(jpf.getPassword());
    } else {
        throw new IOException("User refused to login");
    }

    // get the form to get the cookies
    GetMethod form = new GetMethod(loginuri);
    try {
        if (httpClient.executeMethod(form) != 200) {
            throw new IOException("Can't GET " + loginuri);
        }
    } finally {
        form.releaseConnection();
    }

    // get cookies
    Cookie[] cookies = httpClient.getState().getCookies();
    for (Cookie c : cookies) {
        System.out.println(c);
        if (c.getName().equals("csrftoken")) {
            csrftoken = c.getValue();
            break;
        }
    }

    // now, post
    PostMethod post = new PostMethod(loginuri);
    try {
        post.addRequestHeader("Referer", loginuri);
        NameValuePair params[] = { new NameValuePair("username", username),
                new NameValuePair("password", password), new NameValuePair("csrfmiddlewaretoken", csrftoken) };
        //System.out.println(Arrays.toString(params));
        post.setRequestBody(params);
        httpClient.executeMethod(post);
        System.out.println(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}

From source file:org.jfree.demo.DrawStringDemo.java

/**
 * Displays a primitive font chooser dialog to allow the user to change the font.
 *///from   w  ww.j a va 2 s.  c o m
private void displayFontDialog() {

    final FontChooserPanel panel = new FontChooserPanel(this.drawStringPanel1.getFont());
    final int result = JOptionPane.showConfirmDialog(this, panel, "Font Selection",
            JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

    if (result == JOptionPane.OK_OPTION) {
        this.drawStringPanel1.setFont(panel.getSelectedFont());
        this.drawStringPanel2.setFont(panel.getSelectedFont());
    }

}

From source file:edu.harvard.mcz.imagecapture.DeterminationFrame.java

/**
 * This method initializes jTable   //from w  ww .  jav a2 s  .  c o  m
 *    
 * @return javax.swing.JTable   
 */
private JTable getJTable() {
    if (jTableDeterminations == null) {
        jTableDeterminations = new JTable();
        DeterminationTableModel model = new DeterminationTableModel();
        jTableDeterminations.setModel(model);
        if (determinations != null) {
            jTableDeterminations.setModel(determinations);
        }

        FilteringAgentJComboBox field = new FilteringAgentJComboBox();
        jTableDeterminations.getColumnModel().getColumn(DeterminationTableModel.ROW_IDENTIFIEDBY)
                .setCellEditor(new ComboBoxCellEditor(field));

        setTableColumnEditors();

        jTableDeterminations.setRowHeight(jTableDeterminations.getRowHeight() + 4);

        jTableDeterminations.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    clickedOnDetsRow = ((JTable) e.getComponent()).getSelectedRow();
                    jPopupDets.show(e.getComponent(), e.getX(), e.getY());
                }
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    clickedOnDetsRow = ((JTable) e.getComponent()).getSelectedRow();
                    jPopupDets.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        });

        jPopupDets = new JPopupMenu();
        JMenuItem mntmDeleteRow = new JMenuItem("Delete Row");
        mntmDeleteRow.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    log.debug(clickedOnDetsRow);
                    if (clickedOnDetsRow >= 0) {
                        int ok = JOptionPane.showConfirmDialog(thisFrame, "Delete the selected determination?",
                                "Delete Determination", JOptionPane.OK_CANCEL_OPTION);
                        if (ok == JOptionPane.OK_OPTION) {
                            log.debug("deleting determination row " + clickedOnDetsRow);
                            ((DeterminationTableModel) jTableDeterminations.getModel())
                                    .deleteRow(clickedOnDetsRow);
                        } else {
                            log.debug("determination row delete canceled by user.");
                        }
                    } else {
                        JOptionPane.showMessageDialog(thisFrame, "Unable to select row to delete.");
                    }
                } catch (Exception ex) {
                    log.error(ex.getMessage());
                    JOptionPane.showMessageDialog(thisFrame,
                            "Failed to delete a determination row. " + ex.getMessage());
                }
            }
        });
        jPopupDets.add(mntmDeleteRow);

    }
    return jTableDeterminations;
}

From source file:net.sf.jabref.external.DownloadExternalFile.java

/**
 * Start a download.//  w w w .  j  ava2 s.  c  om
 *
 * @param callback The object to which the filename should be reported when download
 *                 is complete.
 */
public void download(URL url, final DownloadCallback callback) throws IOException {
    String res = url.toString();
    String mimeType;

    // First of all, start the download itself in the background to a temporary file:
    final File tmp = File.createTempFile("jabref_download", "tmp");
    tmp.deleteOnExit();

    URLDownload udl = MonitoredURLDownload.buildMonitoredDownload(frame, url);

    try {
        // TODO: what if this takes long time?
        // TODO: stop editor dialog if this results in an error:
        mimeType = udl.determineMimeType(); // Read MIME type
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(frame, Localization.lang("Invalid URL") + ": " + ex.getMessage(),
                Localization.lang("Download file"), JOptionPane.ERROR_MESSAGE);
        LOGGER.info("Error while downloading " + "'" + res + "'", ex);
        return;
    }
    final URL urlF = url;
    final URLDownload udlF = udl;

    JabRefExecutorService.INSTANCE.execute(() -> {
        try {
            udlF.downloadToFile(tmp);
        } catch (IOException e2) {
            dontShowDialog = true;
            if ((editor != null) && editor.isVisible()) {
                editor.setVisible(false, false);
            }
            JOptionPane.showMessageDialog(frame, Localization.lang("Invalid URL") + ": " + e2.getMessage(),
                    Localization.lang("Download file"), JOptionPane.ERROR_MESSAGE);
            LOGGER.info("Error while downloading " + "'" + urlF + "'", e2);
            return;
        }
        // Download finished: call the method that stops the progress bar etc.:
        SwingUtilities.invokeLater(DownloadExternalFile.this::downloadFinished);
    });

    Optional<ExternalFileType> suggestedType = Optional.empty();
    if (mimeType != null) {
        LOGGER.debug("MIME Type suggested: " + mimeType);
        suggestedType = ExternalFileTypes.getInstance().getExternalFileTypeByMimeType(mimeType);
    }
    // Then, while the download is proceeding, let the user choose the details of the file:
    String suffix;
    if (suggestedType.isPresent()) {
        suffix = suggestedType.get().getExtension();
    } else {
        // If we didn't find a file type from the MIME type, try based on extension:
        suffix = getSuffix(res);
        if (suffix == null) {
            suffix = "";
        }
        suggestedType = ExternalFileTypes.getInstance().getExternalFileTypeByExt(suffix);
    }

    String suggestedName = getSuggestedFileName(suffix);
    List<String> fDirectory = databaseContext.getFileDirectory();
    String directory;
    if (fDirectory.isEmpty()) {
        directory = null;
    } else {
        directory = fDirectory.get(0);
    }
    final String suggestDir = directory == null ? System.getProperty("user.home") : directory;
    File file = new File(new File(suggestDir), suggestedName);
    FileListEntry entry = new FileListEntry("", file.getCanonicalPath(), suggestedType);
    editor = new FileListEntryEditor(frame, entry, true, false, databaseContext);
    editor.getProgressBar().setIndeterminate(true);
    editor.setOkEnabled(false);
    editor.setExternalConfirm(closeEntry -> {
        File f = directory == null ? new File(closeEntry.link) : expandFilename(directory, closeEntry.link);
        if (f.isDirectory()) {
            JOptionPane.showMessageDialog(frame, Localization.lang("Target file cannot be a directory."),
                    Localization.lang("Download file"), JOptionPane.ERROR_MESSAGE);
            return false;
        }
        if (f.exists()) {
            return JOptionPane.showConfirmDialog(frame,
                    Localization.lang("'%0' exists. Overwrite file?", f.getName()),
                    Localization.lang("Download file"), JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION;
        } else {
            return true;
        }
    });
    if (dontShowDialog) {
        return;
    } else {
        editor.setVisible(true, false);
    }
    // Editor closed. Go on:
    if (editor.okPressed()) {
        File toFile = directory == null ? new File(entry.link) : expandFilename(directory, entry.link);
        String dirPrefix;
        if (directory == null) {
            dirPrefix = null;
        } else {
            if (directory.endsWith(System.getProperty("file.separator"))) {
                dirPrefix = directory;
            } else {
                dirPrefix = directory + System.getProperty("file.separator");
            }
        }

        try {
            boolean success = FileUtil.copyFile(tmp, toFile, true);
            if (!success) {
                // OOps, the file exists!
                LOGGER.error("File already exists! DownloadExternalFile.download()");
            }

            // If the local file is in or below the main file directory, change the
            // path to relative:
            if ((directory != null) && entry.link.startsWith(directory)
                    && (entry.link.length() > dirPrefix.length())) {
                entry = new FileListEntry(entry.description, entry.link.substring(dirPrefix.length()),
                        entry.type);
            }

            callback.downloadComplete(entry);
        } catch (IOException ex) {
            LOGGER.warn("Problem downloading file", ex);
        }

        if (!tmp.delete()) {
            LOGGER.info("Cannot delete temporary file");
        }
    } else {
        // Canceled. Just delete the temp file:
        if (downloadFinished && !tmp.delete()) {
            LOGGER.info("Cannot delete temporary file");
        }
    }

}

From source file:com.dmrr.asistenciasx.Horarios.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    try {//from   ww  w  .  j  ava  2s.  co  m
        int x = jTableHorarios.getSelectedRow();
        if (x == -1) {
            JOptionPane.showMessageDialog(this, "Seleccione un profesor primero", "Datos incompletos",
                    JOptionPane.WARNING_MESSAGE);
            return;
        }
        Integer idProfesor = Integer
                .parseInt((String) jTableHorarios.getValueAt(jTableHorarios.getSelectedRow(), 1));

        JPasswordField pf = new JPasswordField();
        String nip = "";
        int okCxl = JOptionPane.showConfirmDialog(null, pf, "Introduzca el NIP del jefe del departamento",
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
        if (okCxl == JOptionPane.OK_OPTION) {
            nip = new String(pf.getPassword());
        } else {
            return;
        }

        org.jsoup.Connection.Response respuesta = Jsoup
                .connect("http://siiauescolar.siiau.udg.mx/wus/gupprincipal.valida_inicio")
                .data("p_codigo_c", "2225255", "p_clave_c", nip).method(org.jsoup.Connection.Method.POST)
                .timeout(0).execute();

        Document login = respuesta.parse();
        String sessionId = respuesta.cookie(getFecha() + "SIIAUSESION");
        String sessionId2 = respuesta.cookie(getFecha() + "SIIAUUDG");

        Document listaHorarios = Jsoup.connect("http://siiauescolar.siiau.udg.mx/wse/sspsecc.consulta_oferta")
                .data("ciclop", "201510", "cup", "J", "deptop", "", "codprofp", "" + idProfesor, "ordenp", "0",
                        "mostrarp", "1000", "tipop", "T", "secp", "A", "regp", "T")
                .userAgent("Mozilla").cookie(getFecha() + "SIIAUSESION", sessionId)
                .cookie(getFecha() + "SIIAUUDG", sessionId2).timeout(0).post();

        Elements tabla = listaHorarios.select("body");
        tabla.select("style").remove();
        Elements font = tabla.select("font");
        font.removeAttr("size");

        System.out.println(tabla.html());

        JEditorPane jEditorPane = new JEditorPane();
        jEditorPane.setEditable(false);

        HTMLEditorKit kit = new HTMLEditorKit();
        jEditorPane.setEditorKit(kit);

        javax.swing.text.Document doc = kit.createDefaultDocument();
        jEditorPane.setDocument(doc);
        jEditorPane.setText(tabla.html());

        JOptionPane.showMessageDialog(null, jEditorPane);

    } catch (IOException ex) {
        Logger.getLogger(Horarios.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.funambol.email.admin.user.ResultSearchUserPanel.java

/**
 * Set up graphic elements for this panel.
 *
 * @throws Exception if error occures during creation of the panel
 *//*  ww  w . j  a  v  a  2 s .  co  m*/
private void init() throws Exception {

    // create objects to display
    this.setLayout(new BorderLayout());
    this.setBorder(BorderFactory.createEmptyBorder());

    // create a model for the user table and pass it to the JTable object
    model = new UserTableModel();
    table = new JTable(model);

    table.setShowGrid(true);
    table.setAutoscrolls(true);
    table.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION);
    JScrollPane scrollpane = new JScrollPane(table);
    table.setPreferredScrollableViewportSize(new Dimension(800, 200));
    table.setFont(GuiFactory.defaultTableFont);
    table.getTableHeader().setFont(GuiFactory.defaultTableHeaderFont);
    this.add(scrollpane, BorderLayout.CENTER);

    //
    // Select user.
    //
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    ListSelectionModel rowSM = table.getSelectionModel();

    rowSM.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent event) {

            if (event.getValueIsAdjusting()) {
                return;
            }

            ListSelectionModel lsm = (ListSelectionModel) event.getSource();

            if (lsm.isSelectionEmpty()) {

                selectedUser = null;
            } else {

                int selectedRow = lsm.getMinSelectionIndex();
                selectedUser = users[selectedRow];
            }
        }
    });

    rowSM.clearSelection();

    table.addMouseListener(new MouseAdapter() {

        public void mouseClicked(MouseEvent event) {

            if (event.getClickCount() < 2) {
                return;
            }

            //
            // If the selected user is already associated to an account
            // then insertion process can't go on.
            //

            String userName = selectedUser.getUsername();
            String value[] = new String[] { userName };
            WhereClause wc = new WhereClause("username", value, WhereClause.OPT_EQ, true);
            MailServerAccount[] tmp = null;
            try {
                tmp = WSDao.getAccounts(wc);
            } catch (Exception e) {
            }

            if (tmp.length > 0) {

                StringBuilder sb = new StringBuilder("The user ");
                sb.append(userName).append(" is already associated to an account");
                Object[] options = { "OK" };
                JOptionPane.showOptionDialog(null, sb.toString(), "Warning", JOptionPane.OK_CANCEL_OPTION,
                        JOptionPane.WARNING_MESSAGE, null, options, options[0]);

            } else {
                //
                // Go to next step.
                //
                step.goToNextStep();
            }
        }
    });

}

From source file:burlov.ultracipher.swing.MainPanel.java

private void deleteCurrentEntry() {
    DataEntry entry = editDataPanel.getData();
    if (entry != null) {
        // int ret = JOptionPane.showOptionDialog(getMainFrame(),
        // "Delete entry?", "Confirm",
        // JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
        // null, JOptionPane.NO_OPTION);
        int ret = JOptionPane.showConfirmDialog(SwingGuiApplication.getInstance().getMainFrame(),
                "Delete entry?", "Warning", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
        if (ret == JOptionPane.OK_OPTION) {
            SwingGuiApplication.getInstance().getDatabase().deleteEntry(entry);
            SwingGuiApplication.getInstance().updateNeedSave(true);
            searchResultModel.removeElement(entry);
            editDataPanel.editData(null, false);
            searchResults.clearSelection();
        }//from www. jav  a 2  s  . c om
    }

}

From source file:com.mirth.connect.plugins.datapruner.DataPrunerPanel.java

public void doStart() {
    final MutableBoolean saveChanges = new MutableBoolean(false);

    if (isSaveEnabled()) {
        if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this,
                "Settings changes must be saved first, would you like to save the settings and prune now?",
                "Select an Option", JOptionPane.OK_CANCEL_OPTION)) {
            if (!validateFields()) {
                return;
            }/*from   w  w  w. j av a  2 s . co m*/

            saveChanges.setValue(true);
        } else {
            return;
        }
    }

    setStartTaskVisible(false);
    final String workingId = parent.startWorking("Starting the data pruner...");

    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        @Override
        protected Void doInBackground() {
            if (saveChanges.getValue()) {
                try {
                    plugin.setPropertiesToServer(getProperties());
                } catch (Exception e) {
                    getFrame().alertThrowable(getFrame(), e);
                    return null;
                }
            }

            try {
                parent.mirthClient.getServlet(DataPrunerServletInterface.class).start();
            } catch (Exception e) {
                parent.alertThrowable(parent, e,
                        "An error occurred while attempting to start the data pruner.");
                return null;
            }

            return null;
        }

        @Override
        public void done() {
            if (saveChanges.getValue()) {
                setSaveEnabled(false);
            }

            parent.stopWorking(workingId);
            updateStatus();
        }
    };

    worker.execute();
}

From source file:com._17od.upm.gui.DatabaseActions.java

public void changeMasterPassword() throws IOException, ProblemReadingDatabaseFile, CryptoException,
        PasswordDatabaseException, TransportException {

    if (getLatestVersionOfDatabase()) {
        //The first task is to get the current master password
        boolean passwordCorrect = false;
        boolean okClicked = true;
        do {//from   w  ww .j  a v  a2 s .  c  om
            char[] password = askUserForPassword(Translator.translate("enterDatabasePassword"));
            if (password == null) {
                okClicked = false;
            } else {
                try {
                    dbPers.load(database.getDatabaseFile(), password);
                    passwordCorrect = true;
                } catch (InvalidPasswordException e) {
                    JOptionPane.showMessageDialog(mainWindow, Translator.translate("incorrectPassword"));
                }
            }
        } while (!passwordCorrect && okClicked);

        //If the master password was entered correctly then the next step is to get the new master password
        if (passwordCorrect == true) {

            final JPasswordField masterPassword = new JPasswordField("");
            boolean passwordsMatch = false;
            Object buttonClicked;

            //Ask the user for the new master password
            //This loop will continue until the two passwords entered match or until the user hits the cancel button
            do {

                JPasswordField confirmedMasterPassword = new JPasswordField("");
                JOptionPane pane = new JOptionPane(
                        new Object[] { Translator.translate("enterNewMasterPassword"), masterPassword,
                                Translator.translate("confirmation"), confirmedMasterPassword },
                        JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
                JDialog dialog = pane.createDialog(mainWindow, Translator.translate("changeMasterPassword"));
                dialog.addWindowFocusListener(new WindowAdapter() {
                    public void windowGainedFocus(WindowEvent e) {
                        masterPassword.requestFocusInWindow();
                    }
                });
                dialog.show();

                buttonClicked = pane.getValue();
                if (buttonClicked.equals(new Integer(JOptionPane.OK_OPTION))) {
                    if (!Arrays.equals(masterPassword.getPassword(), confirmedMasterPassword.getPassword())) {
                        JOptionPane.showMessageDialog(mainWindow, Translator.translate("passwordsDontMatch"));
                    } else {
                        passwordsMatch = true;
                    }
                }

            } while (buttonClicked.equals(new Integer(JOptionPane.OK_OPTION)) && !passwordsMatch);

            //If the user clicked OK and the passwords match then change the database password
            if (buttonClicked.equals(new Integer(JOptionPane.OK_OPTION)) && passwordsMatch) {
                this.dbPers.getEncryptionService().initCipher(masterPassword.getPassword());
                saveDatabase();
            }

        }
    }

}