Example usage for javax.swing JOptionPane showConfirmDialog

List of usage examples for javax.swing JOptionPane showConfirmDialog

Introduction

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

Prototype

public static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType)
        throws HeadlessException 

Source Link

Document

Brings up a dialog where the number of choices is determined by the optionType parameter.

Usage

From source file:me.ryandowling.allmightybot.AllmightyBot.java

public AllmightyBot() {
    if (Files.exists(Utils.getSettingsFile())) {
        try {/*from   w  w w .  ja  v  a2 s  . c  o  m*/
            this.settings = GSON.fromJson(FileUtils.readFileToString(Utils.getSettingsFile().toFile()),
                    Settings.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        this.settings = new Settings();
    }

    if (!this.settings.hasInitialSetupBeenCompleted()) {
        String input = null;

        input = JOptionPane.showInputDialog(null,
                "Please enter the username of the Twitch user " + "to act " + "as the bot", "Twitch Username",
                JOptionPane.QUESTION_MESSAGE);

        if (input == null) {
            logger.error("Failed to input proper things when setting up! Do it properly next time!");
            System.exit(0);
        }

        settings.setTwitchUsername(input);

        input = JOptionPane.showInputDialog(null,
                "Please enter the IRC oauth token of the Twitch user " + "acting as the bot", "Twitch Token",
                JOptionPane.QUESTION_MESSAGE);

        if (input == null) {
            logger.error("Failed to input proper things when setting up! Do it properly next time!");
            System.exit(0);
        }

        settings.setTwitchToken(input);

        input = JOptionPane.showInputDialog(null,
                "Please enter the API token of the Twitch user " + "acting " + "as the bot", "Twitch API Token",
                JOptionPane.QUESTION_MESSAGE);

        if (input == null) {
            logger.error("Failed to input proper things when setting up! Do it properly next time!");
            System.exit(0);
        }

        settings.setTwitchApiToken(input);

        input = JOptionPane.showInputDialog(null,
                "Please enter the API client ID of the application using " + "the Twitch API",
                "Twitch API Client ID", JOptionPane.QUESTION_MESSAGE);

        if (input == null) {
            logger.error("Failed to input proper things when setting up! Do it properly next time!");
            System.exit(0);
        }

        settings.setTwitchApiClientID(input);

        input = JOptionPane.showInputDialog(null,
                "Please enter the username of the Twitch user whose "
                        + "channel you wish to join! Must be in all lowercase",
                "User To Join", JOptionPane.QUESTION_MESSAGE);

        if (input == null) {
            logger.error("Failed to input proper things when setting up! Do it properly next time!");
            System.exit(0);
        }

        settings.setTwitchChannel(input);

        input = JOptionPane.showInputDialog(null,
                "Please enter the name of the caster to display when " + "referencing them", "Casters Name",
                JOptionPane.QUESTION_MESSAGE);

        if (input == null) {
            logger.error("Failed to input proper things when setting up! Do it properly next time!");
            System.exit(0);
        }

        settings.setCastersName(input);

        input = JOptionPane.showInputDialog(null,
                "How often do you want to run the timed messages (in " + "minutes)?", "Timed Messages",
                JOptionPane.QUESTION_MESSAGE);
        try {
            settings.setTimedMessagesInterval(Integer.parseInt(input) * 60);
        } catch (NumberFormatException e) {
            input = null;
        }

        input = JOptionPane.showInputDialog(null, "How long do you want to time people out for when they post "
                + "links after 1 warning (in minutes)?", "Spam Timeouts", JOptionPane.QUESTION_MESSAGE);
        try {
            settings.setLinkTimeoutLength1(Integer.parseInt(input) * 60);
        } catch (NumberFormatException e) {
            input = null;
        }

        input = JOptionPane.showInputDialog(null,
                "How long do you want to time people out for when they post "
                        + "links after 2 and more warnings (in minutes)?",
                "Spam Timeouts", JOptionPane.QUESTION_MESSAGE);
        try {
            settings.setLinkTimeoutLength2(Integer.parseInt(input) * 60);
        } catch (NumberFormatException e) {
            input = null;
        }

        if (input == null) {
            logger.error("Failed to input proper things when setting up! Do it properly next time!");
            System.exit(0);
        }

        int reply = JOptionPane.showConfirmDialog(null,
                "Do you want the bot to announce itself on join " + "(message "
                        + "customisable in the lang.json file after startup)?",
                "Self Announce", JOptionPane.YES_NO_OPTION);
        if (reply != JOptionPane.YES_OPTION) {
            settings.setAnnounceOnJoin(false);
        }

        this.settings.initialSetupComplete();
        this.firstTime = true;
    }
}

From source file:es.emergya.ui.plugins.AdminPanel.java

@Override
public void actionPerformed(ActionEvent e) {
    String cmd = e.getActionCommand();
    if (cmd.indexOf("Seleccionar Tod") == 0) {
        for (int i = 0; i < table.getRowCount(); i++) {
            table.getModel().setValueAt(Boolean.TRUE, i, 0);
        }// www . j  a  va  2s. co m
    } else if (cmd.indexOf("Deseleccionar Tod") == 0) {
        for (int i = 0; i < table.getRowCount(); i++) {
            table.getModel().setValueAt(Boolean.FALSE, i, 0);
        }
    } else if (cmd.indexOf("Eliminar Seleccionad") == 0) {
        boolean alguno = false;
        for (int i = table.getRowCount() - 1; i >= 0 && !alguno; i--) {
            if ((Boolean) table.getModel().getValueAt(i, 0)) {
                alguno = true;
            }
        }

        if (!alguno) {
            return;
        }

        if (JOptionPane.showConfirmDialog(this, "Buttons.delete.confirm", "Selecciona una opcin",
                JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) {
            return;
        }
        Vector<Object> fail = new Vector<Object>();
        int total = 0;
        for (int i = table.getRowCount() - 1; i >= 0; i--) {
            if ((Boolean) table.getModel().getValueAt(i, 0)) {
                DeleteAction a = (DeleteAction) ((JButton) table.getValueAt(i, table.getColumnCount() - 1))
                        .getAction();
                total++;
                if (!a.delete(false)) {
                    fail.add(table.getValueAt(i, 1));
                }

            }
        }

        if (this.father != null) {
            this.father.refresh(null);
            PluginEventHandler.fireChange(this.father);
        }

        if (total == 0) {
            JOptionPane.showMessageDialog(this, "No hay elementos seleccionados para eliminar.", null,
                    JOptionPane.ERROR_MESSAGE);
        }

        if (fail.size() > 0) {
            JOptionPane.showMessageDialog(this, errorString + ":\n" + fail.toString() + "\n" + errorCause, null,
                    JOptionPane.ERROR_MESSAGE);
        }

    } else
        log.error("Comando no encontrado: " + cmd);
}

From source file:jhplot.HPlotChart.java

/**
 * Exports the image to some graphic format.
 *///from   www.  j a  v a2 s  .c o m
protected void exportImage() {

    JFrame jm = getFrame();
    JFileChooser fileChooser = jhplot.gui.CommonGUI.openImageFileChooser(jm);

    if (fileChooser.showDialog(jm, "Save As") == 0) {

        final File scriptFile = fileChooser.getSelectedFile();
        if (scriptFile == null)
            return;
        else if (scriptFile.exists()) {
            int res = JOptionPane.showConfirmDialog(jm, "The file exists. Do you want to overwrite the file?",
                    "", JOptionPane.YES_NO_OPTION);
            if (res == JOptionPane.NO_OPTION)
                return;
        }
        String mess = "write image  file ..";
        JHPlot.showStatusBarText(mess);
        Thread t = new Thread(mess) {
            public void run() {
                export(scriptFile.getAbsolutePath());
            };
        };
        t.start();
    }
}

From source file:condorclient.MainFXMLController.java

@FXML
void pauseButtonFired(ActionEvent event) {
    int delNo = 0;
    int pauseId = 0;
    int n = JOptionPane.showConfirmDialog(null, "??", "",
            JOptionPane.YES_NO_OPTION);
    if (n == JOptionPane.YES_OPTION) {

        //checkboxclusterId
        System.out.print(Thread.currentThread().getName() + "\n");

        URL url = null;/*from   w  w  w.ja  v  a  2s .c o  m*/
        XMLHandler handler = new XMLHandler();
        String scheddStr = handler.getURL("schedd");
        try {
            url = new URL(scheddStr);
        } catch (MalformedURLException e3) {
            // TODO Auto-generated catch block
            e3.printStackTrace();
        }
        Schedd schedd = null;

        try {
            schedd = new Schedd(url);
        } catch (ServiceException ex) {
            Logger.getLogger(CondorClient.class.getName()).log(Level.SEVERE, null, ex);
        }

        //ClassAdStructAttr[]
        int boxToClusterId;

        ClassAd ad = null;//birdbath.ClassAd;
        ClassAdStructAttr[][] classAdArray = null;

        Transaction xact = schedd.createTransaction();
        try {
            xact.begin(30);

        } catch (RemoteException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        int job = 0;
        //s
        final List<?> selectedNodeList = new ArrayList<>(table.getSelectionModel().getSelectedItems());
        for (Object o : selectedNodeList) {
            if (o instanceof ObservableDisplayedClassAd) {
                pauseId = Integer.parseInt(((ObservableDisplayedClassAd) o).getClusterId());
            }
        }
        //e

        String findreq = "owner==\"" + condoruser + "\"&&ClusterId==" + pauseId;

        try {
            classAdArray = schedd.getJobAds(findreq);
        } catch (RemoteException ex) {
            Logger.getLogger(MainFXMLController.class.getName()).log(Level.SEVERE, null, ex);
        }
        String showJobStatus = null;
        for (ClassAdStructAttr[] x : classAdArray) {
            ad = new ClassAd(x);
            job = Integer.parseInt(ad.get("ProcId"));

            status = Integer.valueOf(ad.get("JobStatus"));
            showJobStatus = statusName[status];
            try {
                if (showJobStatus.equals("") || showJobStatus.equals("?")
                        || showJobStatus.equals("")) {
                    xact.holdJob(pauseId, job, "");
                } else {//??
                    if (showJobStatus.equals("?") || showJobStatus.equals("")) {
                        JOptionPane.showMessageDialog(null, "?????");
                        return;
                    }
                }
                // System.out.print("ts.getClusterId():" + showClusterId + "\n");
            } catch (RemoteException ex) {
                Logger.getLogger(MainFXMLController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        try {
            xact.commit();
        } catch (RemoteException e) {

            e.printStackTrace();
        }

    } else if (n == JOptionPane.NO_OPTION) {
        System.out.println("qu xiao");

    }
}

From source file:com.tiempometa.muestradatos.JMuestraDatos.java

private void menuItem2ActionPerformed(ActionEvent e) {
    int response = JOptionPane.showConfirmDialog(null, "Seguro que deseas cerrar la aplicacin?",
            "Cerrar Programa", JOptionPane.WARNING_MESSAGE);
    if (response == JOptionPane.YES_OPTION) {
        ReaderContext.stopReading();/*from w  w  w.ja va2s. c om*/
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            ReaderContext.disconnectUsbReader();
        } catch (ReaderException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        this.dispose();
    }
}

From source file:captureplugin.drivers.defaultdriver.AdditionalParams.java

/**
 *  Remove was pressed/*from   w  w w .  jav a  2s  .  c om*/
 */
protected void removePressed() {
    if (mList.getSelectedValue() == null) {
        return;
    }

    mDeleting = true;
    int result = JOptionPane.showConfirmDialog(this, mLocalizer.msg("Delete", "Delete Parameter?"),
            mLocalizer.msg("Additional", "Additional Parameters"), JOptionPane.YES_NO_OPTION);

    if (result == JOptionPane.YES_OPTION) {

        mSelectedEntry = null;

        int num = mList.getSelectedIndex();

        mListModel.removeElement(mList.getSelectedValue());

        if (num + 1 > mListModel.size()) {
            mList.setSelectedIndex(mListModel.size() - 1);
        } else if (mListModel.size() > 0) {
            mList.setSelectedIndex(num);
        }
    }
    mDeleting = false;
}

From source file:com.floreantpos.config.ui.DatabaseConfigurationDialog.java

public void actionPerformed(ActionEvent e) {
    try {//from   w  w  w.j a  v  a 2 s .  c  o m
        String command = e.getActionCommand();

        Database selectedDb = (Database) databaseCombo.getSelectedItem();

        final String providerName = selectedDb.getProviderName();
        final String databaseURL = tfServerAddress.getText();
        final String databasePort = tfServerPort.getText();
        final String databaseName = tfDatabaseName.getText();
        final String user = tfUserName.getText();
        final String pass = new String(tfPassword.getPassword());

        final String connectionString = selectedDb.getConnectString(databaseURL, databasePort, databaseName);
        final String hibernateDialect = selectedDb.getHibernateDialect();
        final String driverClass = selectedDb.getHibernateConnectionDriverClass();

        if (CANCEL.equalsIgnoreCase(command)) {
            dispose();
            return;
        }

        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

        Application.getInstance().setSystemInitialized(false);
        saveConfig(selectedDb, providerName, databaseURL, databasePort, databaseName, user, pass,
                connectionString, hibernateDialect);

        if (TEST.equalsIgnoreCase(command)) {
            try {
                DatabaseUtil.checkConnection(connectionString, hibernateDialect, driverClass, user, pass);
            } catch (DatabaseConnectionException e1) {
                JOptionPane.showMessageDialog(this, Messages.getString("DatabaseConfigurationDialog.32")); //$NON-NLS-1$
                return;
            }

            connectionSuccess = true;
            JOptionPane.showMessageDialog(this, Messages.getString("DatabaseConfigurationDialog.31")); //$NON-NLS-1$
        } else if (UPDATE_DATABASE.equals(command)) {
            int i = JOptionPane.showConfirmDialog(this, Messages.getString("DatabaseConfigurationDialog.0"), //$NON-NLS-1$
                    Messages.getString("DatabaseConfigurationDialog.1"), JOptionPane.YES_NO_OPTION); //$NON-NLS-1$
            if (i != JOptionPane.YES_OPTION) {
                return;
            }

            //isAuthorizedToPerformDbChange();

            setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

            boolean databaseUpdated = DatabaseUtil.updateDatabase(connectionString, hibernateDialect,
                    driverClass, user, pass);
            if (databaseUpdated) {
                connectionSuccess = true;
                JOptionPane.showMessageDialog(DatabaseConfigurationDialog.this,
                        Messages.getString("DatabaseConfigurationDialog.2")); //$NON-NLS-1$
            } else {
                JOptionPane.showMessageDialog(DatabaseConfigurationDialog.this,
                        Messages.getString("DatabaseConfigurationDialog.3")); //$NON-NLS-1$
            }
        } else if (CREATE_DATABASE.equals(command)) {

            int i = JOptionPane.showConfirmDialog(this, Messages.getString("DatabaseConfigurationDialog.33"), //$NON-NLS-1$
                    Messages.getString("DatabaseConfigurationDialog.34"), JOptionPane.YES_NO_OPTION); //$NON-NLS-1$
            if (i != JOptionPane.YES_OPTION) {
                return;
            }

            i = JOptionPane.showConfirmDialog(this, Messages.getString("DatabaseConfigurationDialog.4"), //$NON-NLS-1$
                    Messages.getString("DatabaseConfigurationDialog.5"), JOptionPane.YES_NO_OPTION); //$NON-NLS-1$
            boolean generateSampleData = false;
            if (i == JOptionPane.YES_OPTION)
                generateSampleData = true;

            setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

            String createDbConnectString = selectedDb.getCreateDbConnectString(databaseURL, databasePort,
                    databaseName);

            boolean databaseCreated = DatabaseUtil.createDatabase(createDbConnectString, hibernateDialect,
                    driverClass, user, pass, generateSampleData);

            if (databaseCreated) {
                JOptionPane.showMessageDialog(DatabaseConfigurationDialog.this,
                        Messages.getString("DatabaseConfigurationDialog.6") + //$NON-NLS-1$
                                Messages.getString("DatabaseConfigurationDialog.7")); //$NON-NLS-1$

                Main.restart();
                connectionSuccess = true;
            } else {
                JOptionPane.showMessageDialog(DatabaseConfigurationDialog.this,
                        Messages.getString("DatabaseConfigurationDialog.36")); //$NON-NLS-1$
            }
        } else if (SAVE.equalsIgnoreCase(command)) {
            if (connectionSuccess) {
                Application.getInstance().initializeSystem();
            }
            dispose();
        }
    } catch (Exception e2) {
        PosLog.error(getClass(), e2);
        POSMessageDialog.showMessage(this, e2.getMessage());
    } finally {
        setCursor(Cursor.getDefaultCursor());
    }
}

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

private boolean saveDatabase(File file, boolean selectedOnly, Charset encoding) throws SaveException {
    SaveSession session;//from w w  w . j  ava2  s . c  o  m
    frame.block();
    try {
        SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs)
                .withEncoding(encoding);
        BibDatabaseWriter databaseWriter = new BibDatabaseWriter();
        if (selectedOnly) {
            session = databaseWriter.savePartOfDatabase(panel.getBibDatabaseContext(), prefs,
                    panel.getSelectedEntries());

        } else {
            session = databaseWriter.saveDatabase(panel.getBibDatabaseContext(), prefs);

        }
        panel.registerUndoableChanges(session);

    } catch (UnsupportedCharsetException ex2) {
        JOptionPane.showMessageDialog(frame,
                Localization.lang("Could not save file.") + Localization
                        .lang("Character encoding '%0' is not supported.", encoding.displayName()),
                Localization.lang("Save database"), JOptionPane.ERROR_MESSAGE);
        throw new SaveException("rt");
    } catch (SaveException ex) {
        if (ex == SaveException.FILE_LOCKED) {
            throw ex;
        }
        if (ex.specificEntry()) {
            // Error occured during processing of
            // be. Highlight it:
            int row = panel.mainTable.findEntry(ex.getEntry());
            int topShow = Math.max(0, row - 3);
            panel.mainTable.setRowSelectionInterval(row, row);
            panel.mainTable.scrollTo(topShow);
            panel.showEntry(ex.getEntry());
        } else {
            LOGGER.error("Problem saving file", ex);
        }

        JOptionPane.showMessageDialog(frame,
                Localization.lang("Could not save file.") + ".\n" + ex.getMessage(),
                Localization.lang("Save database"), JOptionPane.ERROR_MESSAGE);
        throw new SaveException("rt");

    } finally {
        frame.unblock();
    }

    boolean commit = true;
    if (!session.getWriter().couldEncodeAll()) {
        FormBuilder builder = FormBuilder.create()
                .layout(new FormLayout("left:pref, 4dlu, fill:pref", "pref, 4dlu, pref"));
        JTextArea ta = new JTextArea(session.getWriter().getProblemCharacters());
        ta.setEditable(false);
        builder.add(Localization.lang("The chosen encoding '%0' could not encode the following characters:",
                session.getEncoding().displayName())).xy(1, 1);
        builder.add(ta).xy(3, 1);
        builder.add(Localization.lang("What do you want to do?")).xy(1, 3);
        String tryDiff = Localization.lang("Try different encoding");
        int answer = JOptionPane.showOptionDialog(frame, builder.getPanel(), Localization.lang("Save database"),
                JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null,
                new String[] { Localization.lang("Save"), tryDiff, Localization.lang("Cancel") }, tryDiff);

        if (answer == JOptionPane.NO_OPTION) {
            // The user wants to use another encoding.
            Object choice = JOptionPane.showInputDialog(frame, Localization.lang("Select encoding"),
                    Localization.lang("Save database"), JOptionPane.QUESTION_MESSAGE, null,
                    Encodings.ENCODINGS_DISPLAYNAMES, encoding);
            if (choice == null) {
                commit = false;
            } else {
                Charset newEncoding = Charset.forName((String) choice);
                return saveDatabase(file, selectedOnly, newEncoding);
            }
        } else if (answer == JOptionPane.CANCEL_OPTION) {
            commit = false;
        }

    }

    try {
        if (commit) {
            session.commit(file);
            panel.setEncoding(encoding); // Make sure to remember which encoding we used.
        } else {
            session.cancel();
        }
    } catch (SaveException e) {
        int ans = JOptionPane.showConfirmDialog(null,
                Localization.lang("Save failed during backup creation") + ". "
                        + Localization.lang("Save without backup?"),
                Localization.lang("Unable to create backup"), JOptionPane.YES_NO_OPTION);
        if (ans == JOptionPane.YES_OPTION) {
            session.setUseBackup(false);
            session.commit(file);
            panel.setEncoding(encoding);
        } else {
            commit = false;
        }
    }

    return commit;
}

From source file:net.sf.keystore_explorer.gui.dialogs.DViewCertCsrPem.java

private void exportPressed() {
    File chosenFile = null;//  ww w.  j av  a  2 s  . c o  m
    FileWriter fw = null;

    String title;
    if (cert != null) {
        title = res.getString("DViewCertCsrPem.ExportPemCertificate.Title");
    } else {
        title = res.getString("DViewCertCsrPem.ExportPemCsr.Title");
    }
    try {
        String certPem = jtaPem.getText();

        JFileChooser chooser = FileChooserFactory.getX509FileChooser();
        chooser.setCurrentDirectory(CurrentDirectory.get());
        chooser.setDialogTitle(title);
        chooser.setMultiSelectionEnabled(false);

        int rtnValue = JavaFXFileChooser.isFxAvailable() ? chooser.showSaveDialog(this)
                : chooser.showDialog(this, res.getString("DViewCertCsrPem.ChooseExportFile.button"));

        if (rtnValue != JFileChooser.APPROVE_OPTION) {
            return;
        }

        chosenFile = chooser.getSelectedFile();
        CurrentDirectory.updateForFile(chosenFile);

        if (chosenFile.isFile()) {
            String message = MessageFormat.format(res.getString("DViewCertCsrPem.OverWriteFile.message"),
                    chosenFile);

            int selected = JOptionPane.showConfirmDialog(this, message, title, JOptionPane.YES_NO_OPTION);
            if (selected != JOptionPane.YES_OPTION) {
                return;
            }
        }

        fw = new FileWriter(chosenFile);
        fw.write(certPem);
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(this,
                MessageFormat.format(res.getString("DViewCertCsrPem.NoWriteFile.message"), chosenFile), title,
                JOptionPane.WARNING_MESSAGE);
        return;
    } catch (Exception ex) {
        DError.displayError(this, ex);
        return;
    } finally {
        IOUtils.closeQuietly(fw);
    }

    JOptionPane.showMessageDialog(this, res.getString("DViewCertCsrPem.ExportPemCertificateSuccessful.message"),
            title, JOptionPane.INFORMATION_MESSAGE);
}

From source file:QueryConnector.java

private static boolean confirm(String msg) {
    return JOptionPane.showConfirmDialog(null, msg, tr("CONFIRM_DIALOG_TITLE"),
            JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION;
}