Example usage for javax.swing JOptionPane OK_OPTION

List of usage examples for javax.swing JOptionPane OK_OPTION

Introduction

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

Prototype

int OK_OPTION

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

Click Source Link

Document

Return value form class method if OK is chosen.

Usage

From source file:captureplugin.drivers.DeviceCreatorDialog.java

/**
 * Create the Device/*from  w w  w. ja va  2s  .  c  o  m*/
 *
 * @return Device
 */
public DeviceIf createDevice() {

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

    return ((DriverIf) mDriverCombo.getSelectedItem()).createDevice(mName.getText().trim());
}

From source file:fi.elfcloud.client.dialog.ModifyDataItemDialog.java

@Override
public int showDialog() {
    setVisible(true);/* w w w . java  2  s. co m*/
    if (answer) {
        return JOptionPane.OK_OPTION;
    }
    return JOptionPane.CANCEL_OPTION;
}

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

/**
 * Create an AbstractAction for performing an export operation.
 *
 * @param frame//from   www  .  j a  v a  2 s  .  co m
 *            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();//from   w  ww.  j  a  va  2  s. c  o  m
        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  w w .  j  a  v a  2s.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 w w.  j  a v  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 .  ja va2  s .c  o m
 *
 * @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   w  ww.  j  av  a 2s  . c om*/
        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.sec.ose.osi.sdk.protexsdk.discovery.report.DefaultEntityListCreator.java

protected ReportEntityList buildEntityListFromHTML(BufferedReader htmlReportReader,
        ArrayList<String> entityKeyList, ArrayList<String> duplicationCheckingField) {
    ReportEntityList reportEntityList = new ReportEntityList();
    ReportEntity reportEntity = null;//from  w  w  w  .j  av a 2 s .  c  o m
    String tmpLine = null;

    if (duplicationCheckingField == null) {
        duplicationCheckingField = new ArrayList<String>();
    }

    int insertedCnt = 0;

    try {
        StringBuffer tmpValue = new StringBuffer("");
        while ((tmpLine = htmlReportReader.readLine()) != null) {
            tmpLine = tmpLine.trim();
            if (tmpLine.startsWith("<tr ")) {
                reportEntity = new ReportEntity();
                int index = 0;
                while ((tmpLine = htmlReportReader.readLine()) != null) {
                    tmpLine = tmpLine.trim();
                    if (tmpLine.startsWith("<td ")) {
                        while ((tmpLine = htmlReportReader.readLine()) != null) {
                            tmpLine = tmpLine.trim();
                            if (tmpLine.startsWith("</td>")) {
                                String key = entityKeyList.get(index);
                                String value = "";

                                if (key.equals(ReportInfo.COMPARE_CODE_MATCHES.COMPARE_CODE_MATCHES_LINK)) {
                                    value = extractURL(tmpValue);
                                } else {
                                    value = removeTag(tmpValue);
                                }
                                reportEntity.setValue(key, value);
                                tmpValue.setLength(0);
                                ++index;
                                break;
                            }
                            tmpValue.append(tmpLine);
                        }
                    }
                    if (tmpLine.startsWith("</tr>")) {
                        if (hasNoData(entityKeyList, index)) {
                            break;
                        }
                        reportEntityList.addEntity(reportEntity);
                        insertedCnt++;
                        if (insertedCnt % 10000 == 0) {
                            log.debug("buildEntityList insertedCnt: " + insertedCnt);
                        }
                        break;
                    }
                }
            }
            if (tmpLine.startsWith(HTML_DATA_TABLE_END_TAG)) {
                break;
            }
        }
    } catch (IOException e) {
        log.warn(e);
        String[] buttonOK = { "OK" };
        JOptionPane.showOptionDialog(null, "Out Of Memory Error", "Java heap space", JOptionPane.OK_OPTION,
                JOptionPane.ERROR_MESSAGE, null, buttonOK, "OK");
    }
    log.debug("buildEntityList insertedCnt finally : " + insertedCnt);
    return reportEntityList;
}

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();
        }// w  ww  .j a v  a 2  s.  c om
    }

}