Example usage for javax.swing JOptionPane YES_NO_OPTION

List of usage examples for javax.swing JOptionPane YES_NO_OPTION

Introduction

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

Prototype

int YES_NO_OPTION

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

Click Source Link

Document

Type used for showConfirmDialog.

Usage

From source file:edu.ku.brc.ui.UIRegistry.java

/**
 * Asks Yes or No question using a JOptionPane
 * @param yesKey the resource key for the Yes button
 * @param noKey the resource key for the No button
 * @param nonL10NMsg the message or question NOT Localized
 * @param titleKey the resource key for the Dialog Title
 * @return JOptionPane.NO_OPTION or JOptionPane.YES_OPTION
 *///  www  .  ja v  a2s . c o  m
public static int askYesNoLocalized(final String yesKey, final String noKey, final String nonL10NMsg,
        final String titleKey) {
    int userChoice = JOptionPane.NO_OPTION;
    Object[] options = { getResourceString(yesKey), getResourceString(noKey) };

    userChoice = JOptionPane.showOptionDialog(UIRegistry.getMostRecentWindow(), nonL10NMsg,
            getResourceString(titleKey), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,
            options[0]);
    return userChoice;
}

From source file:ded.ui.DiagramController.java

/** Prompt user for file name and save to it. */
public void chooseAndSaveToFile() {
    // Prompt for a file name, confirming if the file already exists.
    String result = this.fileName;
    while (true) {
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(this.currentFileChooserDirectory);
        chooser.addChoosableFileFilter(new FileNameExtensionFilter("Diagram Editor Files (.ded)", "ded"));
        int res = chooser.showSaveDialog(this);
        if (res != JFileChooser.APPROVE_OPTION) {
            return;
        }//  w  ww .  j  a  va 2s. c  o m
        this.currentFileChooserDirectory = chooser.getCurrentDirectory();
        result = chooser.getSelectedFile().getAbsolutePath();

        if (new File(result).exists()) {
            res = JOptionPane.showConfirmDialog(this,
                    "A file called \"" + result + "\" already exists.  Overwrite it?", "Confirm Overwrite",
                    JOptionPane.YES_NO_OPTION);
            if (res != JOptionPane.YES_OPTION) {
                continue; // Ask again.
            }
        }

        break;
    }

    // Save to the chosen file.
    this.saveToNamedFile(result);
}

From source file:edu.ku.brc.specify.tasks.ReportsBaseTask.java

/**
 * Processes all Commands of type LABELS.
 * @param cmdAction the command to be processed
 *///  w  w  w .  ja v  a  2  s.c om
protected void processReportCommands(final CommandAction cmdAction) {

    //---------------------------------------------------------------------------
    // This Code here needs to be refactored and moved to the NavBoxAction
    // so it can happen in a single generic place (Each task has this code)
    //---------------------------------------------------------------------------
    /*if (cmdAction.getData() instanceof RecordSetIFace)
    {
    if (((RecordSetIFace)cmdAction.getData()).getDbTableId() != cmdAction.getTableId())
    {
        JOptionPane.showMessageDialog(null, getResourceString("ERROR_RECORDSET_TABLEID"), getResourceString("Error"), JOptionPane.ERROR_MESSAGE);
        return;
    }
    }*/

    Object data = cmdAction.getData();
    UsageTracker.incrUsageCount(
            "RP." + cmdAction.getType() + (data != null ? ("." + data.getClass().getSimpleName()) : ""));

    if (cmdAction.isAction(NEWRECORDSET_ACTION)) {
        if (cmdAction.getData() instanceof GhostActionable) {
            GhostActionable ga = (GhostActionable) cmdAction.getData();
            GhostMouseInputAdapter gpa = ga.getMouseInputAdapter();

            for (NavBoxItemIFace nbi : reportsList) {
                if (nbi instanceof GhostActionable) {
                    gpa.addGhostDropListener(new GhostActionableDropManager(UIRegistry.getGlassPane(),
                            nbi.getUIComponent(), ga));
                }
            }
        }
    } else if (cmdAction.isAction(PRINT_REPORT)) {
        if (data instanceof CommandAction && ((CommandAction) data).isAction(RUN_REPORT)) {
            runReport(cmdAction);
        }
        //            if (cmdAction.getData() instanceof CommandAction && ((CommandAction)cmdAction.getData()).isAction(OPEN_EDITOR))
        //            {
        //                openIReportEditor(cmdAction);
        //            }
        if (cmdAction.getData() instanceof RecordSetIFace) {
            RecordSetIFace rs = (RecordSetIFace) cmdAction.getData();
            if (rs.getDbTableId() != null && rs.getDbTableId() == SpReport.getClassTableId()
                    || cmdAction.getProperty("spreport") != null) {
                runReport(cmdAction);
            } else {
                printReport(cmdAction);
            }
        } else {
            if (data instanceof CommandAction && ((CommandAction) data).isAction(PRINT_REPORT)) {
                printReport((CommandAction) data);
            } else {
                printReport(cmdAction);
            }
        }
    }
    //        else if (cmdAction.isAction(OPEN_EDITOR))
    //        {
    //            openIReportEditor(cmdAction);
    //        }
    else if (cmdAction.isAction(RUN_REPORT)) {
        boolean doRun = true;
        if (data instanceof CommandAction && ((CommandAction) data).isAction(PRINT_REPORT)) {
            doRun = ((CommandAction) data).getProperty("spreport") != null;
        }
        if (doRun) {
            runReport(cmdAction);
        } else {
            printReport((CommandAction) data);
        }
    } else if (cmdAction.isAction(REFRESH)) {
        refreshCommands();

    } else if (cmdAction.isAction(IMPORT)) {
        importReport();

    } else if (cmdAction.isAction(PRINT_GRID)) {
        printGrid(cmdAction);

    } else if (cmdAction.isAction(DELETE_CMD_ACT)) {
        RecordSetIFace recordSet = null;
        if (cmdAction.getData() instanceof RecordSetIFace) {
            recordSet = (RecordSetIFace) cmdAction.getData();

        } else if (cmdAction.getData() instanceof RolloverCommand) {
            RolloverCommand roc = (RolloverCommand) cmdAction.getData();
            if (roc.getData() instanceof RecordSetIFace) {
                recordSet = (RecordSetIFace) roc.getData();
            }
        }
        if (recordSet != null || cmdAction.getProperties().get("name") != null) {
            String theName;
            String theTitle;
            if (recordSet != null) {
                theName = recordSet.getName();
                theTitle = theName;
            } else {
                theName = cmdAction.getProperties().getProperty("name");
                //currently the description of the appResource is used as the 'title' for the command button.
                //theTitle = ((AppResourceIFace)cmdAction.getProperties().get("appresource")).getDescription();
                theTitle = cmdAction.getProperties().getProperty("title");
            }
            int option = JOptionPane.showOptionDialog(UIRegistry.getMostRecentWindow(),
                    String.format(UIRegistry.getResourceString("REP_CONFIRM_DELETE"), theName),
                    UIRegistry.getResourceString("REP_CONFIRM_DELETE_TITLE"), JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE, null, null, JOptionPane.NO_OPTION); // I18N

            if (option == JOptionPane.YES_OPTION) {
                Integer resId = Integer.class.cast(cmdAction.getProperty("spappresourceid"));
                Integer resOrRepId = null;
                Integer repId = null;
                if (resId != null) {
                    resOrRepId = resId;
                }
                RecordSetItemIFace item = recordSet == null ? null : recordSet.getOnlyItem();
                if (item != null) {
                    repId = item.getRecordId();
                    resOrRepId = repId;
                }
                deleteReportAndResource(repId, resId);
                deleteReportFromUI(theTitle);
                if (resOrRepId != null) {
                    CommandDispatcher.dispatch(new CommandAction(REPORTS, REPORT_DELETED, resOrRepId));
                } else {
                    //what can you do?
                }
            }
        }
    }
}

From source file:com.ga.forms.DailyLogAddUI.java

private void checkInOutButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkInOutButtonActionPerformed
    DailyLogRecord log = new DailyLogRecord();
    if (DailyLogAddUI.checkIn && !DailyLogAddUI.breakDone) {
        args = new HashMap();
        DailyLogAddUI.breakDone = true;/*  www . j a  v a2  s  .  c  om*/
        args.put("checked-in", Boolean.toString(DailyLogAddUI.checkIn));
        args.put("had-break", Boolean.toString(DailyLogAddUI.breakDone));
        args.put("checked-out", Boolean.toString(DailyLogAddUI.checkOut));
        if (yesRdButton.isSelected() == true) {
            this.timeOnBreak = "00:30";
        } else if (customRdButton.isSelected() == true) {
            this.timeOnBreak = customBreakTimeTextField.getText();
        } else {
            this.timeOnBreak = "00:00";
        }
        log.setDailyLogRecord(dateDisplayLbl.getText(), dayDisplayLbl.getText(),
                checkInTimeCombo.getSelectedItem().toString(), "", this.timeOnBreak, "", "", "", args);
        doc = (DBObject) JSON.parse(log.getDailyLogRecord().toString());
        args.clear();
        args.put("date", dateDisplayLbl.getText());
        log.updateRecord(doc, args);
    } else if (DailyLogAddUI.checkIn && DailyLogAddUI.breakDone && !DailyLogAddUI.checkOut) {
        args = new HashMap();
        DailyLogAddUI.checkOut = true;
        args.put("checked-in", Boolean.toString(DailyLogAddUI.checkIn));
        args.put("had-break", Boolean.toString(DailyLogAddUI.breakDone));
        args.put("checked-out", Boolean.toString(DailyLogAddUI.checkOut));
        DailyLogDuration durationAgent = new DailyLogDuration();
        durationAgent.calculateCurrentDuration(checkInTimeCombo.getSelectedItem().toString(), this.timeOnBreak,
                checkOutTimeCombo.getSelectedItem().toString());
        this.duration = durationAgent.getCurrentDuration();

        JFrame parent = new JFrame();
        JOptionPane optionPane = new JOptionPane("Duration: " + this.duration + "\n\nDo you want to Check Out?",
                JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);
        JDialog msgDialog = optionPane.createDialog(parent, "DLM");
        msgDialog.setVisible(true);

        if (optionPane.getValue().equals(0)) {
            int hours = Integer.parseInt(this.duration.split(":")[0]);
            int minutes = Integer.parseInt(this.duration.split(":")[1]);
            if (hours < 9) {
                durationAgent.calculateUnderTime(this.duration);
                this.underTime = durationAgent.getUnderTime();
                this.overTime = "00:00";
            } else if (hours >= 9 && minutes > 0 && minutes < 60) {
                this.underTime = "00:00";
                durationAgent.calculateOverTime(this.duration);
                this.overTime = durationAgent.getOverTime();

            } else {
                this.underTime = "00:00";
                this.overTime = "00:00";
            }
            log.setDailyLogRecord(dateDisplayLbl.getText(), dayDisplayLbl.getText(),
                    checkInTimeCombo.getSelectedItem().toString(),
                    checkOutTimeCombo.getSelectedItem().toString(), this.timeOnBreak, this.duration,
                    this.underTime, this.overTime, args);
            doc = (DBObject) JSON.parse(log.getDailyLogRecord().toString());
            args.clear();
            args.put("date", dateDisplayLbl.getText());
            log.updateRecord(doc, args);
        } else {
            msgDialog.dispose();
        }
    } else {
        args = new HashMap();
        DailyLogAddUI.checkIn = true;
        args.put("checked-in", Boolean.toString(DailyLogAddUI.checkIn));
        args.put("had-break", Boolean.toString(DailyLogAddUI.breakDone));
        args.put("checked-out", Boolean.toString(DailyLogAddUI.checkOut));
        log.setDailyLogRecord(dateDisplayLbl.getText(), dayDisplayLbl.getText(),
                checkInTimeCombo.getSelectedItem().toString(), "", "", "", "", "", args);
        doc = (DBObject) JSON.parse(log.getDailyLogRecord().toString());
        log.insertRecord(doc);

    }

}

From source file:net.sf.jabref.gui.entryeditor.EntryEditor.java

private boolean storeSource() {
    BibtexParser bibtexParser = new BibtexParser(new StringReader(source.getText()));

    try {//from  w  w  w . j  a  va 2 s  .  co  m
        ParserResult parserResult = bibtexParser.parse();
        BibDatabase database = parserResult.getDatabase();

        if (database.getEntryCount() > 1) {
            throw new IllegalStateException("More than one entry found.");
        }

        if (!database.hasEntries()) {
            if (parserResult.hasWarnings()) {
                // put the warning into as exception text -> it will be displayed to the user
                throw new IllegalStateException(parserResult.warnings().get(0));
            } else {
                throw new IllegalStateException("No entries found.");
            }
        }

        NamedCompound compound = new NamedCompound(Localization.lang("source edit"));
        BibEntry newEntry = database.getEntries().get(0);
        String newKey = newEntry.getCiteKey();
        boolean entryChanged = false;
        boolean duplicateWarning = false;
        boolean emptyWarning = (newKey == null) || newKey.isEmpty();

        if (panel.getDatabase().setCiteKeyForEntry(entry, newKey)) {
            duplicateWarning = true;
        }

        // First, remove fields that the user has removed.
        for (String field : entry.getFieldNames()) {
            if (InternalBibtexFields.isDisplayableField(field) && !newEntry.hasField(field)) {
                compound.addEdit(new UndoableFieldChange(entry, field, entry.getField(field), null));
                entry.clearField(field);
                entryChanged = true;
            }
        }

        // Then set all fields that have been set by the user.
        for (String field : newEntry.getFieldNames()) {
            String oldValue = entry.getField(field);
            String newValue = newEntry.getField(field);
            if (!Objects.equals(oldValue, newValue)) {
                // Test if the field is legally set.
                new LatexFieldFormatter(LatexFieldFormatterPreferences.fromPreferences(Globals.prefs))
                        .format(newValue, field);

                compound.addEdit(new UndoableFieldChange(entry, field, oldValue, newValue));
                entry.setField(field, newValue);
                entryChanged = true;
            }
        }

        // See if the user has changed the entry type:
        if (!Objects.equals(newEntry.getType(), entry.getType())) {
            compound.addEdit(new UndoableChangeType(entry, entry.getType(), newEntry.getType()));
            entry.setType(newEntry.getType());
            entryChanged = true;
        }
        compound.end();

        if (!entryChanged) {
            return true;
        }

        panel.getUndoManager().addEdit(compound);

        if (duplicateWarning) {
            warnDuplicateBibtexkey();
        } else if (emptyWarning) {
            warnEmptyBibtexkey();
        } else {
            panel.output(Localization.lang("Stored entry") + '.');
        }

        lastSourceStringAccepted = source.getText();
        // Update UI
        // TODO: we need to repaint the entryeditor if fields that are not displayed have been added
        panel.updateEntryEditorIfShowing();
        lastSourceAccepted = true;
        updateSource = true;
        // TODO: does updating work properly after source stored?
        panel.markBaseChanged();

        SwingUtilities.invokeLater(() -> {
            final int row = panel.getMainTable().findEntry(entry);
            if (row >= 0) {
                panel.getMainTable().ensureVisible(row);
            }
        });

        return true;
    } catch (IllegalStateException | IOException ex) {
        // The source couldn't be parsed, so the user is given an
        // error message, and the choice to keep or revert the contents
        // of the source text field.
        updateSource = false;
        lastSourceAccepted = false;
        tabbed.setSelectedComponent(srcPanel);

        Object[] options = { Localization.lang("Edit"), Localization.lang("Revert to original source") };

        int answer = JOptionPane.showOptionDialog(frame, Localization.lang("Error") + ": " + ex.getMessage(),
                Localization.lang("Problem with parsing entry"), JOptionPane.YES_NO_OPTION,
                JOptionPane.ERROR_MESSAGE, null, options, options[0]);

        if (answer != 0) {
            updateSource = true;
            updateSource();
        }

        LOGGER.debug("Incorrect source", ex);

        return false;
    }
}

From source file:userinterface.Citizen.CitizenWorkAreaJPanel.java

private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
    int selectedRow = vitalSigntable.getSelectedRow();
    if (selectedRow >= 0) {
        int dialogButton = JOptionPane.YES_NO_OPTION;
        int dialogResult = JOptionPane.showConfirmDialog(null, "Would you like to delete Vital Sign?",
                "Warning", dialogButton);
        if (dialogResult == JOptionPane.YES_OPTION) {
            VitalSign vs = (VitalSign) vitalSigntable.getValueAt(selectedRow, 0);
            account.getCitizen().getHealthReport().deleteVitalSign(vs);
            populateTable();/*www . j  a va 2  s .co  m*/
            resetfields();

        }
    } else {
        JOptionPane.showMessageDialog(null, "Please select a row from the table first", "Warning",
                JOptionPane.WARNING_MESSAGE);
    }
}

From source file:com.alvermont.terraj.fracplanet.ui.AbstractTerrainViewerFrame.java

private void saveImageItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_saveImageItemActionPerformed
{//GEN-HEADEREND:event_saveImageItemActionPerformed

    final int choice = this.pngChooser.showSaveDialog(this);

    if (choice == JFileChooser.APPROVE_OPTION) {
        if (!this.pngChooser.getSelectedFile().isFile() || (JOptionPane.showConfirmDialog(this,
                "This file already exists. Do you want to\n" + "overwrite it?", "Replace File?",
                JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)) {
            try {
                display.getCanvas().getContext().makeCurrent();

                try {
                    final File target = FileUtils.addExtension(this.pngChooser.getSelectedFile(), ".png");

                    Screenshot.writeToFile(target, display.getCanvas().getWidth(),
                            display.getCanvas().getHeight());
                } finally {
                    display.getCanvas().getContext().release();
                }/*ww w .  j  a  va  2 s . c  o  m*/
            } catch (IOException ioe) {
                log.error("Error writing image file", ioe);

                JOptionPane.showMessageDialog(this,
                        "Error: " + ioe.getMessage() + "\nCheck log file for full details", "Error Saving",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}

From source file:ded.ui.DiagramController.java

/** Save to the current file name.  If there is no file name,
  * prompt for a name. *//*from   w w  w  . ja v  a 2 s . com*/
public void saveCurrentFile() {
    if (this.fileName.isEmpty()) {
        this.chooseAndSaveToFile();
    } else {
        if (this.importedFile) {
            int res = SwingUtil.confirmationBox(this, "This diagram was loaded from \"" + this.fileName
                    + "\", which uses the old binary ER format from the "
                    + "C++ ERED implementation.  If you save the file, it "
                    + "will be overwritten with the new JSON-based format "
                    + "used by the Java-based Diagram Editor, which the " + "C++ ERED cannot read.\n" + "\n"
                    + "In order to avoid confusion, it is probably best to "
                    + "save the new file with the \".ded\" extension rather "
                    + "than the traditional \".er\" extension so that others "
                    + "will know to use Ded to read it.\n" + "\n" + "Overwrite with the new format anyway?",
                    "Confirm Overwrite of Imported File", JOptionPane.YES_NO_OPTION);
            if (res != JOptionPane.YES_OPTION) {
                return;
            }
        }

        this.saveToNamedFile(this.fileName);
    }
}

From source file:beproject.MainGUI.java

/**
 * This function perform initialization activities
 * @param evt //from  ww  w. ja  v a  2s.c om
 */
private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown

    formRef = this;
    Initializer.checkStatus();

    List tmp = ScheduledMoviesList.getMovieNames();
    for (Object tmp1 : tmp) {
        movieNamesComboBox.addItem(tmp1);
    }

    if (!tmp.isEmpty() && JOptionPane.showConfirmDialog(null, "Resume Twitter Streaming?", "HypeAnalyzer",
            JOptionPane.YES_NO_OPTION) == 0) {
        myTwitterObj = new myTwitter(twitterStatusLabel);
        twitterThread = new Thread(myTwitterObj);
        twitterThread.setPriority(Thread.MAX_PRIORITY);
        twitterThread.start();
        startStreamingCheckBoxMenuItem.setSelected(true);
        twitterStatusLabel.setText("STREAMING TWEETS");
    }

    try {
        URL url = new URL("http://www.google.com");
        url.openConnection().connect();
        internetConnectionLabel.setText("Internet Status: Available");
    } catch (IOException ex) {
    }
    try {
        stmt = inConn.createStatement();
    } catch (SQLException e) {
        ExceptionManager.handleException(e, "Error Connecting to MySql");
    }
    databaseConnectionLabel.setText("Connected to database");
    liveTweetAnalysis();

    myRegression = new Regression();

    updateAllGraphs();
    /*new Thread(new Runnable(){
            
    @Override
    public void run() {
        try{
            int i=0;
            //PreparedStatement pstmt=Initializer.outConn2.prepareStatement("");
            while(true){
                ResultSet rs=stmt.executeQuery("select username from tweets where country='' limit "+i+", 30");
                if(rs.first()==false)
                    break;
                else
                    i+=30;
                while(rs.next()){
                    String user=rs.getString(1);
                    String country=MyRestAPI.getUserCountry(user);
                }
            }
                    
                    
        }catch(Exception e){
            e.printStackTrace();
        }
    }
            
    }).start();
    */
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                createTimeLine();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }).start();
}

From source file:nosqltools.MainForm.java

private void connect_DBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connect_DBActionPerformed

    Panel_Text.setVisible(false);
    Panel_Hierarchical.setVisible(false);
    Panel_Table.setVisible(false);
    Panel_Compare.setVisible(false);
    Panel_Compare_Upper.setVisible(false);
    Panel_Connect.setVisible(true);

    Text_MessageBar.setText(Initializations.WAITINGFORCONNECTION);
    Text_MessageBar.setForeground(Color.ORANGE);
    if (dbcon.isConnectionSuccess()) {
        if (dbcon.checkDatabaseConnection()) {
            int result = JOptionPane.showConfirmDialog(null,
                    "A connection to MongoDB" + "already exists. Are you sure you want to disconnect and open "
                            + "a different connection?",
                    "Confirm", JOptionPane.YES_NO_OPTION);

            if (result == JOptionPane.YES_OPTION) {
                dbcon.closeConnection();
                connect();//from  w ww .ja v  a  2s .c  o m
            }
        } else {
            Text_MessageBar.setText(Initializations.MONGOSERVERERROR);
            Text_MessageBar.setForeground(Color.RED);
            JOptionPane.showMessageDialog(null, Initializations.MONGOSERVERERROR, "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
    } else {
        connect();
    }

}