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:course_generator.frmMain.java

/**
 * Define a new starting point from the current position in the main table
 *///from   www .j a va 2s . co m
protected void NewStartPoint() {
    if (Track.data.isEmpty())
        return;

    int start = TableMain.getSelectedRow();
    if (start < 0)
        return;

    //-- Confirmation dialog
    Object[] options = { " " + bundle.getString("frmMain.NewStartYes") + " ",
            " " + bundle.getString("frmMain.NewStartNo") + " " };
    int ret = JOptionPane.showOptionDialog(this, bundle.getString("frmMain.NewStartMessage"),
            bundle.getString("frmMain.NewStartTitle"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE,
            null, options, options[1]);

    //-- Ok! Let's go
    if (ret == JOptionPane.YES_OPTION) {
        Track.NewStartingPoint(start);

        //-- Move the cursor to the first line of the data table
        TableMain.setRowSelectionInterval(0, 0);
        Rectangle rect = TableMain.getCellRect(0, 0, true);
        TableMain.scrollRectToVisible(rect);

        Track.isCalculated = false;
        Track.isModified = true;

        //-- Refresh
        RefreshStatusbar(Track);
        RefreshTableMain();
        RefreshResume();
        RefreshStat(false);

        //Refresh the marker position on the map
        RefreshCurrentPosMarker(Track.data.get(0).getLatitude(), Track.data.get(0).getLongitude());
    }
}

From source file:marytts.tools.redstart.AdminWindow.java

private void jMenuItem_ImportTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_ImportTextActionPerformed
    JFileChooser fc = new JFileChooser(new File(voiceFolderPathString));
    fc.setDialogTitle("Choose text file to import");
    //fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int returnVal = fc.showOpenDialog(this);
    if (returnVal != JFileChooser.APPROVE_OPTION)
        return;//w w  w .  j ava 2  s  . c  o  m
    File file = fc.getSelectedFile();
    if (file == null)
        return;
    String[] lines = null;
    try {
        lines = StringUtils.readTextFile(file.getAbsolutePath(), "UTF-8");
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    if (lines == null || lines.length == 0)
        return;
    Object[] options = new Object[] { "Keep first column", "Discard first column" };
    int answer = JOptionPane.showOptionDialog(this,
            "File contains " + lines.length + " sentences.\n" + "Sample line:\n" + lines[0] + "\n"
                    + "Keep or discard first column?",
            "Import details", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,
            options[1]);
    boolean discardFirstColumn = (answer == JOptionPane.NO_OPTION);

    String prefix = (String) JOptionPane.showInputDialog(this,
            "Prefix to use for individual sentence filenames:", "Choose filename prefix",
            JOptionPane.PLAIN_MESSAGE, null, null, "s");
    int numDigits = (int) Math.log10(lines.length) + 1;
    String pattern = prefix + "%0" + numDigits + "d.txt";
    File scriptFile = new File(voiceFolderPathString + "/" + file.getName() + ".script.txt");
    PrintWriter scriptWriter = null;
    try {
        scriptWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(scriptFile), "UTF-8"));
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this,
                "Cannot write to script file " + scriptFile.getAbsolutePath() + ":\n" + e.getMessage());
        if (scriptWriter != null)
            scriptWriter.close();
        return;
    }
    File textFolder = getPromptFolderPath();

    // if filename ends with ".txt_tr" then it has also transcriptions in it
    String selectedFile_ext = FilenameUtils.getExtension(file.getName());
    Boolean inputHasAlsoTranscription = false;
    File transcriptionFolder = new File("");

    // transcription folder name, and makedir
    if (selectedFile_ext.equals("txt_tr")) {
        System.out.println("txt_tr");
        if (lines.length % 2 == 0) {
            // even
        } else {
            // odd
            System.err.println(".txt_tr file has an odd number of lines, so it's corrupted, exiting.");
            System.exit(0);
        }
        inputHasAlsoTranscription = true;
        String transcriptionFolderName = voiceFolderPathString + AdminWindow.TRANSCRIPTION_FOLDER_NAME;
        transcriptionFolder = new File(transcriptionFolderName);
        if (transcriptionFolder.exists()) {
            System.out.println("transcription folder already exists");
        } else {
            if (transcriptionFolder.mkdirs()) {
                System.out.println("transcription folder created");
            } else {
                System.err.println("Cannot create transcription folder -- exiting.");
                System.exit(0);
            }
        }
    } else {
        System.out.println("input file extension is not txt_tr, but " + selectedFile_ext
                + ", so it contains ortographic sentences without transcriptions.");
    }

    for (int i = 0; i < lines.length; i++) {
        String line = lines[i];
        if (discardFirstColumn)
            line = line.substring(line.indexOf(' ') + 1);
        int sent_index = i + 1;
        if (inputHasAlsoTranscription == true) {
            sent_index = i / 2 + 1;
        }

        String filename = String.format(pattern, sent_index);
        System.out.println(filename + " " + line);
        File textFile = new File(textFolder, filename);
        if (textFile.exists()) {
            JOptionPane.showMessageDialog(this, "Cannot writing file " + filename + ":\n" + "File exists!\n"
                    + "Aborting text file import.");
            return;
        }
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(textFile), "UTF-8"));
            pw.println(line);
            scriptWriter.println(filename.substring(0, filename.lastIndexOf('.')) + " " + line);
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(this, "Error writing file " + filename + ":\n" + ioe.getMessage());
            ioe.printStackTrace();
            return;
        } finally {
            if (pw != null)
                pw.close();
        }

        // transcription case:
        if (inputHasAlsoTranscription == true) {
            // modify pattern: best would be something like sed "s/.txt$/.tr$/"
            // easy but dirty:
            String transc_pattern = pattern.replace(".txt", ".tr");
            filename = String.format(transc_pattern, sent_index);
            i++;
            line = lines[i];
            if (discardFirstColumn)
                line = line.substring(line.indexOf(' ') + 1);
            File transcriptionTextFile = new File(transcriptionFolder, filename);
            if (transcriptionTextFile.exists()) {
                JOptionPane.showMessageDialog(this, "Cannot writing file " + transcriptionTextFile.getName()
                        + ":\n" + "File exists!\n" + "Aborting text file import.");
                return;
            }
            pw = null;
            try {
                pw = new PrintWriter(
                        new OutputStreamWriter(new FileOutputStream(transcriptionTextFile), "UTF-8"));
                pw.println(line);
                scriptWriter.println(filename.substring(0, filename.lastIndexOf('.')) + " " + line);
            } catch (IOException ioe) {
                JOptionPane.showMessageDialog(this,
                        "Error writing file " + filename + ":\n" + ioe.getMessage());
                ioe.printStackTrace();
                return;
            } finally {
                if (pw != null)
                    pw.close();
            }
        }

    }
    scriptWriter.close();
    setupVoice();
}

From source file:com.sec.ose.osi.ui.frm.main.identification.codematch.JPanCodeMatchMain.java

public UECodeMatch exportUIEntity(String projectName) {

    String tmpComponentName = "";
    String tmpVersionName = "";
    String tmpLicenseName = "";

    String originComponentName = "";
    String originVersionName = "";
    String originLicenseName = "";

    String currentComponentName = "";
    String currentVersionName = "";
    String currentLicenseName = "";

    String newComponentName = "";
    String newVersionName = "";
    String newLicenseName = "";

    String matchedFile = "";
    String comment = IdentifyMediator.getInstance().getComment();

    int compositeType = IdentificationConstantValue.CODE_MATCH_TYPE;
    int row = 0;/*from   w  w  w. ja  va 2 s .c  o  m*/
    JTableMatchedInfo jTableMatchedInfo = jPanelTableCardLayout.getSelectedTable();
    String status = "";

    switch (pathType) {
    case SelectedFilePathInfo.SINGLE_FILE_TYPE: {
        row = jTableMatchedInfo.getSelectedRow();
        tmpComponentName = String
                .valueOf(jTableMatchedInfo.getValueAt(row, TableModelForCMFile.COL_COMPONENT_NAME));
        tmpVersionName = String
                .valueOf(jTableMatchedInfo.getValueAt(row, TableModelForCMFile.COL_VERSION_NAME));
        tmpLicenseName = String
                .valueOf(jTableMatchedInfo.getValueAt(row, TableModelForCMFile.COL_LICENSE_NAME));
        matchedFile = String.valueOf(jTableMatchedInfo.getValueAt(row, TableModelForCMFile.COL_MATCHED_FILE));
        status = String.valueOf(jTableMatchedInfo.getValueAt(row, TableModelForCMFile.COL_STATUS));
    }
        break;
    case SelectedFilePathInfo.MULTIPLE_FILE_TYPE: {
        row = jTableMatchedInfo.getSelectedRow();
        tmpComponentName = String
                .valueOf(jTableMatchedInfo.getValueAt(row, TableModelForCMMultipleFile.COL_COMPONENT_NAME));
        tmpVersionName = String
                .valueOf(jTableMatchedInfo.getValueAt(row, TableModelForCMMultipleFile.COL_VERSION_NAME));
        tmpLicenseName = String
                .valueOf(jTableMatchedInfo.getValueAt(row, TableModelForCMMultipleFile.COL_LICENSE_NAME));
        status = String.valueOf(jTableMatchedInfo.getValueAt(row, TableModelForCMMultipleFile.COL_STATUS));
        compositeType |= IdentificationConstantValue.FOLDER_TYPE;
    }
        break;
    case SelectedFilePathInfo.FOLDER_TYPE:
    case SelectedFilePathInfo.PROJECT_TYPE: {
        row = jTableMatchedInfo.getSelectedRow();
        tmpComponentName = String
                .valueOf(jTableMatchedInfo.getValueAt(row, TableModelForCMFolder.COL_COMPONENT_NAME));
        tmpVersionName = String
                .valueOf(jTableMatchedInfo.getValueAt(row, TableModelForCMFolder.COL_VERSION_NAME));
        tmpLicenseName = String
                .valueOf(jTableMatchedInfo.getValueAt(row, TableModelForCMFolder.COL_LICENSE_NAME));
        status = String.valueOf(jTableMatchedInfo.getValueAt(row, TableModelForCMFolder.COL_STATUS));
        compositeType |= IdentificationConstantValue.FOLDER_TYPE;
    }
        break;
    }

    currentComponentName = DCCodeMatch.getCurrentValue(tmpComponentName);
    currentVersionName = DCCodeMatch.getCurrentValue(tmpVersionName);
    currentLicenseName = DCCodeMatch.getCurrentValue(tmpLicenseName);

    originComponentName = DCCodeMatch.getOriginValue(tmpComponentName);
    originVersionName = DCCodeMatch.getOriginValue(tmpVersionName);
    originLicenseName = DCCodeMatch.getOriginValue(tmpLicenseName);

    if (rdbtnOpt1IConform.isSelected()) {
        compositeType |= IdentificationConstantValue.STANDARD_COMPONENT_TYPE;
        newComponentName = String
                .valueOf(jTableMatchedInfo.getValueAt(row, TableModelForCMFile.COL_COMPONENT_NAME));
        newLicenseName = String
                .valueOf(jTableMatchedInfo.getValueAt(row, TableModelForCMFile.COL_LICENSE_NAME));
        newVersionName = String
                .valueOf(jTableMatchedInfo.getValueAt(row, TableModelForCMFile.COL_VERSION_NAME));
        if (newVersionName.equals("Unspecified"))
            newVersionName = "";

    } else if (rdbtnOpt2ICannotFind.isSelected()) {
        status = String.valueOf(jTableMatchedInfo.getValueAt(row, TableModelForCMFile.COL_STATUS));
        if (("Pending".equals(status))
                && (IdentifyMediator.getInstance().getSelectedLicenseName().length() == 0)) {
            JOptionPane.showOptionDialog(null, "Select License.", "Pending identification",
                    JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE, null, buttonOK, "OK");
            return null;
        }

        if (("Pending".equals(status)) && (cbComponent.getSelectedItem() == null)) {
            JOptionPane.showOptionDialog(null, "Component must be completed.", "Pending identification",
                    JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE, null, buttonOK, "OK");
            return null;
        } else {
            newComponentName = String.valueOf(cbComponent.getSelectedItem());
            newLicenseName = String.valueOf(cbCmLicense.getSelectedItem());

        }
        compositeType |= IdentificationConstantValue.STANDARD_COMPONENT_TYPE;

    } else if (rdbtnOpt3Internal.isSelected()) {
        newComponentName = OPTION3_DECLARED_NOT_OPEN_SOURCE;

    } else if (rdbtnOpt4NotAlarm.isSelected()) {
        newComponentName = OPTION4_DECLARED_DO_NOT_ALARM_AGAIN;
    }

    log.debug("[JPanCodeMatchMain.exportUIEntity()] newComponentName : " + newComponentName);
    log.debug("[JPanCodeMatchMain.exportUIEntity()] newVersionName : " + newVersionName);
    log.debug("[JPanCodeMatchMain.exportUIEntity()] newLicenseName : " + newLicenseName);

    UECodeMatch xUECodeMatch = new UECodeMatch(originComponentName, originVersionName, originLicenseName,
            currentComponentName, currentVersionName, currentLicenseName, newComponentName, newVersionName,
            newLicenseName, matchedFile, compositeType, comment, status);
    return xUECodeMatch;
}

From source file:com.freedomotic.jfrontend.MainWindow.java

/**
 * /*from ww  w.j  a  va 2 s  . c om*/
 * @param evt 
 */
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
    String[] buttons = { i18n.msg("form_compilation"), i18n.msg("send_log"), i18n.msg("delete") };
    int option = JOptionPane.showOptionDialog(null, i18n.msg("report_issue_dialog"), i18n.msg("report_issue"),
            JOptionPane.WARNING_MESSAGE, 0, null, buttons, buttons[2]);
    switch (option) {
    case 0:
        this.openGoogleForm();
        break;
    case 1:
        this.sendLogByMail();
        break;
    default:
        break;
    }
}

From source file:Form.Principal.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    try {/*from w w w .j a  va  2 s. c o m*/
        String Comando = null;
        if (jTextField3.getText().equalsIgnoreCase("") || jTextField5.getText().equalsIgnoreCase("")
                || jTextField6.getText().equalsIgnoreCase("") || jTextField7.getText().equalsIgnoreCase("")
                || jTextField8.getText().equalsIgnoreCase("") || jTextField9.getText().equalsIgnoreCase("")
                || jTextField10.getText().equalsIgnoreCase("") || jTextField11.getText().equalsIgnoreCase("")) {
            Object[] options = { "Aceptar" };
            JOptionPane.showOptionDialog(null, "Datos incompletos", "Aviso", JOptionPane.DEFAULT_OPTION,
                    JOptionPane.WARNING_MESSAGE, null, options, options[0]);
        } else {
            Comando = "INSERT INTO cliente VALUES (default,'" + jTextField5.getText() + "','"
                    + jTextField6.getText() + "','" + jTextField10.getText() + "','" + jTextField9.getText()
                    + "','" + jTextField7.getText() + "','" + jTextField8.getText() + "','"
                    + jTextField3.getText() + "','" + jTextField11.getText() + "'); ";
            Funcion.Update(st, Comando);
            Autocompletar.removeAllItems();
            Autocompletar = new TextAutoCompleter(jTextField2);
            Comandos = Funcion.Select(st, "SELECT * FROM cliente;");
            try {
                while (Comandos.next()) {
                    Autocompletar.addItem(Comandos.getString("RFC"));
                }
            } catch (SQLException ex) {
                //Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
            }
            //*******Limpiar
            jTextField5.setText("");
            jTextField6.setText("");
            jTextField10.setText("");
            jTextField8.setText("");
            jTextField9.setText("");
            jTextField7.setText("");
            jTextField3.setText("");
            jTextField11.setText("");
            jPanel7.setVisible(false);
            jButton2.setVisible(false);
            //jPanel6.setVisible(false);
            //jButton1.setVisible(false);
            jButton1.setEnabled(true);

            Object[] options = { "Aceptar" };
            JOptionPane.showOptionDialog(null, "Exito!", "Nuevo cliente", JOptionPane.DEFAULT_OPTION,
                    JOptionPane.WARNING_MESSAGE, null, options, options[0]);

            /*jButton8.setVisible(true);
            jButton9.setVisible(true);
            jButton10.setVisible(true);
            jButton3.setVisible(true);
            jButton11.setVisible(true); 
            FechaSistema();
            factura();
            CrearPanelPDF();*/
        }

    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Error en los datos" + e.getMessage());
    }

}

From source file:com.nikonhacker.gui.EmulatorUI.java

private void openDecodeDialog() {
    JTextField sourceFile = new JTextField();
    JTextField destinationDir = new JTextField();
    FileSelectionPanel sourceFileSelectionPanel = new FileSelectionPanel("Source file", sourceFile, false);
    sourceFileSelectionPanel.setFileFilter(".bin", "Firmware file (*.bin)");
    final JComponent[] inputs = new JComponent[] { sourceFileSelectionPanel,
            new FileSelectionPanel("Destination dir", destinationDir, true) };
    if (JOptionPane.OK_OPTION == JOptionPane.showOptionDialog(this, inputs,
            "Choose source file and destination dir", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE,
            null, null, JOptionPane.DEFAULT_OPTION)) {
        try {/*from   www . j a v a2  s .  c  o m*/
            new FirmwareDecoder().decode(sourceFile.getText(), destinationDir.getText(), false);
            JOptionPane.showMessageDialog(this, "Decoding complete", "Done", JOptionPane.INFORMATION_MESSAGE);
        } catch (FirmwareFormatException e) {
            JOptionPane.showMessageDialog(this, e.getMessage() + "\nPlease see console for full stack trace",
                    "Error decoding files", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }
    }
}

From source file:edu.ku.brc.specify.Specify.java

/**
 * /* w  w  w  .j  a  v a  2 s . c o  m*/
 */
protected void checkForUpdates() {
    //UIRegistry.displayInfoMsgDlg("checkForUpdates(): checking for updates");

    String errKey = null;
    //NOTE: it looks like the "UPDATE_PATH" resource and the update url setting in i4jparams.conf need to be kept in sync
    String updatePath = UIRegistry.getResourceString("UPDATE_PATH");
    boolean doTheUpdate = false;
    try {
        // if automatic update checking is disabled, disable intentional
        // update checking also...
        // ...seems like a good idea.
        Boolean isReleaseManagedGlobally = AppContextMgr.getInstance().getClassObject(Institution.class)
                .getIsReleaseManagedGlobally();
        //         AppPreferences localPrefs = AppPreferences.getLocalPrefs();
        //         String VERSION_CHECK = "version_check.auto";
        //         boolean localChk4VersionUpdate = localPrefs.getBoolean(VERSION_CHECK, true);

        //UIRegistry.displayInfoMsgDlg("checkForUpdates(): isReleaseManagedGlobally=" + isReleaseManagedGlobally);

        doTheUpdate = (isReleaseManagedGlobally == null
                || !isReleaseManagedGlobally) /*&& localChk4VersionUpdate*/;

        //UIRegistry.displayInfoMsgDlg("checkForUpdates(): checking for updates at " + updatePath);

        UpdateDescriptor updateDesc = UpdateChecker.getUpdateDescriptor(updatePath,
                ApplicationDisplayMode.UNATTENDED);
        //UIRegistry.displayInfoMsgDlg("checkForUpdates(): UpdateDescriptor=" + updateDesc);

        if (updateDesc != null) {
            UpdateDescriptorEntry entry = updateDesc.getPossibleUpdateEntry();
            //UIRegistry.displayInfoMsgDlg("checkForUpdates(): PossibleUpdate=" + (entry != null ? entry.getNewVersion() : entry));

            if (entry != null) {
                Object[] options = { getResourceString("Specify.INSTALLUPDATE"), //$NON-NLS-1$
                        getResourceString("Specify.SKIP") //$NON-NLS-1$
                };
                if (doTheUpdate) {
                    int userChoice = JOptionPane.showOptionDialog(UIRegistry.getTopWindow(),
                            getLocalizedMessage("Specify.UPDATE_AVAIL", entry.getNewVersion()), //$NON-NLS-1$
                            getResourceString("Specify.UPDATE_AVAIL_TITLE"), //$NON-NLS-1$
                            JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,
                            options[0]);

                    if (userChoice == JOptionPane.YES_OPTION) {
                        if (!doExit(false)) {
                            return;
                        }

                    } else {
                        return;
                    }
                } else {
                    JOptionPane.showMessageDialog(UIRegistry.getTopWindow(),
                            getLocalizedMessage("Specify.UPDATE_AVAIL_BUT_UPDATES_DISABLED", //$NON-NLS-1$
                                    entry.getNewVersion()), getResourceString("Specify.UPDATE_AVAIL_TITLE"), //$NON-NLS-1$
                            JOptionPane.INFORMATION_MESSAGE);

                }
            } else {
                errKey = "Specify.NO_UPDATE_AVAIL";
            }
        } else {
            errKey = UPDATE_CHK_ERROR;
        }
    } catch (Exception ex) {
        errKey = UPDATE_CHK_ERROR;
        ex.printStackTrace();
        log.error(ex);
    }

    if (errKey != null) {
        log.error(String.format("Update Error: %s - %s", errKey, updatePath));
        UIRegistry.showLocalizedError(errKey);
        return;
    }

    if (doTheUpdate) {
        try {
            ApplicationLauncher.Callback callback = new ApplicationLauncher.Callback() {
                public void exited(int exitValue) {
                    log.error("exitValue: " + exitValue);
                    // startApp(doConfig);
                }

                public void prepareShutdown() {
                    log.error("prepareShutdown");

                }
            };
            //UIRegistry.displayInfoMsgDlg("checkForUpdates(): launching update application");
            ApplicationLauncher.launchApplication("100", getProxySettings(), true, callback);

        } catch (Exception ex) {
            log.error(ex);
            log.error("EXPCEPTION");
        }
    } else {
        //UIRegistry.showLocalizedMsg(UIRegistry.getResourceString("UPDATES_DISABLED_FOR_INSTALLATION"));
        return;
    }

}

From source file:edu.ku.brc.af.ui.forms.FormViewObj.java

public boolean isDataCompleteAndValid(final boolean throwAwayOnDiscard) {
    //log.debug((formValidator != null) +" "+ formValidator.hasChanged() +"  "+mvParent.isTopLevel() +" "+ mvParent.hasChanged());

    // Figure out if it is New and whether it has changed or is incomplete
    boolean isNewAndComplete = true;
    if (mvParent != null) {
        Object topParentData = mvParent.getTopLevel().getData();
        if (topParentData != null && topParentData instanceof FormDataObjIFace) {
            if (((FormDataObjIFace) topParentData).getId() == null) {
                if (formValidator != null && dataObj != null) {
                    isNewAndComplete = formValidator.isFormValid();
                }/*from ww w. java  2  s.  co  m*/
            }
        }
    }

    //log.debug("Form     Val: "+(formValidator != null && formValidator.hasChanged()));
    //log.debug("mvParent Val: "+(mvParent != null && mvParent.isTopLevel() && mvParent.hasChanged()));

    //if ((formValidator != null && formValidator.hasChanged()) ||
    //    (mvParent != null && mvParent.isTopLevel() && mvParent.hasChanged()))
    if (!doingDiscard && mvParent != null && mvParent.isTopLevel() && mvParent.hasChanged()) {
        try {
            doingDiscard = true;
            String title = null;
            if (dataObj != null) {
                if (tableInfo == null) {
                    tableInfo = DBTableIdMgr.getInstance()
                            .getByShortClassName(dataObj.getClass().getSimpleName());
                }

                title = tableInfo != null ? tableInfo.getTitle() : null;

                if (StringUtils.isEmpty(title)) {
                    title = UIHelper.makeNamePretty(dataObj.getClass().getSimpleName());
                }
            }

            if (StringUtils.isEmpty(title)) {
                title = "data"; // I18N, not really sure what to put here.
            }

            // For the DISCARD
            // Since JOptionPane doesn't have a YES_CANCEL_OPTION 
            // I have to use YES_NO_OPTION and since this is a Discard question
            // the rv has completely different meanings:
            // YES -> Means don't save (Discard) and close dialog (return true)
            // NO  -> Means do nothing so return false

            String[] optionLabels;
            int dlgOptions;
            int defaultRV;
            if (!isNewAndComplete || (formValidator != null && !formValidator.isFormValid())) {
                dlgOptions = JOptionPane.YES_NO_OPTION;
                optionLabels = new String[] { getResourceString("DiscardChangesBtn"),
                        getResourceString("CANCEL") };
                defaultRV = JOptionPane.NO_OPTION;
            } else {
                dlgOptions = JOptionPane.YES_NO_CANCEL_OPTION;
                optionLabels = new String[] { getResourceString("SaveChangesBtn"),
                        getResourceString("DiscardChangesBtn"), getResourceString("CANCEL") };
                defaultRV = JOptionPane.CANCEL_OPTION;
            }

            int rv = JOptionPane.showOptionDialog(UIRegistry.getTopWindow(),
                    isNewAndComplete ? UIRegistry.getLocalizedMessage("DiscardChanges", title)
                            : UIRegistry.getLocalizedMessage("SaveChanges", title),
                    isNewAndComplete ? getResourceString("DiscardChangesTitle")
                            : getResourceString("SaveChangesTitle"),
                    dlgOptions, JOptionPane.QUESTION_MESSAGE, null, optionLabels, optionLabels[0]);

            if (rv == JOptionPane.CLOSED_OPTION) {
                rv = defaultRV;
            }

            if (dlgOptions == JOptionPane.YES_NO_OPTION) {
                if (rv == JOptionPane.YES_OPTION) {
                    discardCurrentObject(throwAwayOnDiscard);
                    return true;

                } else if (rv == JOptionPane.NO_OPTION) {
                    return false;
                }

            } else {
                if (rv == JOptionPane.YES_OPTION) {
                    return saveObject();

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

                } else if (rv == JOptionPane.NO_OPTION) {
                    // NO means Discard
                    discardCurrentObject(throwAwayOnDiscard);
                    return true;
                }
            }
        } finally {
            doingDiscard = false;
        }

    } else {
        return true;
    }
    return isNewAndComplete;
}

From source file:com.nikonhacker.gui.EmulatorUI.java

private void openEncodeDialog() {
    JTextField destinationFile = new JTextField();
    JTextField sourceFile1 = new JTextField();
    JTextField sourceFile2 = new JTextField();
    FileSelectionPanel destinationFileSelectionPanel = new FileSelectionPanel("Destination file",
            destinationFile, false);//  w  ww  .j  a va2  s  .  co m
    destinationFileSelectionPanel.setFileFilter(".bin", "Encoded firmware file (*.bin)");
    FileSelectionPanel sourceFile1SelectionPanel = new FileSelectionPanel("Source file 1", sourceFile1, false);
    destinationFileSelectionPanel.setFileFilter("a*.bin", "Decoded A firmware file (a*.bin)");
    FileSelectionPanel sourceFile2SelectionPanel = new FileSelectionPanel("Source file 2", sourceFile2, false);
    destinationFileSelectionPanel.setFileFilter("b*.bin", "Decoded B firmware file (b*.bin)");
    final JComponent[] inputs = new JComponent[] { destinationFileSelectionPanel, sourceFile1SelectionPanel,
            sourceFile2SelectionPanel };
    if (JOptionPane.OK_OPTION == JOptionPane.showOptionDialog(this, inputs,
            "Choose target encoded file and source files", JOptionPane.OK_CANCEL_OPTION,
            JOptionPane.PLAIN_MESSAGE, null, null, JOptionPane.DEFAULT_OPTION)) {
        try {
            ArrayList<String> inputFilenames = new ArrayList<String>();
            inputFilenames.add(sourceFile1.getText());
            inputFilenames.add(sourceFile2.getText());
            new FirmwareEncoder().encode(inputFilenames, destinationFile.getText());
            JOptionPane.showMessageDialog(this, "Encoding complete", "Done", JOptionPane.INFORMATION_MESSAGE);
        } catch (FirmwareFormatException e) {
            JOptionPane.showMessageDialog(this, e.getMessage() + "\nPlease see console for full stack trace",
                    "Error encoding files", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }
    }
}

From source file:com.nikonhacker.gui.EmulatorUI.java

private void openDecodeNkldDialog() {
    JTextField sourceFile = new JTextField();
    JTextField destinationFile = new JTextField();
    FileSelectionPanel sourceFileSelectionPanel = new FileSelectionPanel("Source file", sourceFile, false);
    sourceFileSelectionPanel.setFileFilter("nkld*.bin", "Lens correction data file (nkld*.bin)");
    final JComponent[] inputs = new JComponent[] { sourceFileSelectionPanel,
            new FileSelectionPanel("Destination file", destinationFile, true) };
    if (JOptionPane.OK_OPTION == JOptionPane.showOptionDialog(this, inputs,
            "Choose source file and destination dir", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE,
            null, null, JOptionPane.DEFAULT_OPTION)) {
        try {//  w  w w  .ja  va 2s  .  com
            new NkldDecoder().decode(sourceFile.getText(), destinationFile.getText(), false);
            JOptionPane
                    .showMessageDialog(
                            this, "Decoding complete.\nFile '"
                                    + new File(destinationFile.getText()).getAbsolutePath() + "' was created.",
                            "Done", JOptionPane.INFORMATION_MESSAGE);
        } catch (FirmwareFormatException e) {
            JOptionPane.showMessageDialog(this, e.getMessage() + "\nPlease see console for full stack trace",
                    "Error decoding files", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }
    }
}