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:com.jvms.i18neditor.editor.Editor.java

public void createProject(Path dir, ResourceType type) {
    try {/*from ww  w.  j  ava 2s .  c om*/
        Preconditions.checkArgument(Files.isDirectory(dir));

        if (!closeCurrentProject()) {
            return;
        }

        List<Resource> resourceList = Resources.get(dir, settings.getResourceName(), Optional.empty());
        if (!resourceList.isEmpty()) {
            boolean importProject = Dialogs.showConfirmDialog(this,
                    MessageBundle.get("dialogs.project.new.conflict.title"),
                    MessageBundle.get("dialogs.project.new.conflict.text"), JOptionPane.YES_NO_OPTION);
            if (importProject) {
                importProject(dir, false);
                return;
            }
        }

        clearUI();
        project = new EditorProject(dir);
        restoreProjectState(project);
        project.setResourceType(type);

        if (type == ResourceType.Properties) {
            Resource resource = Resources.create(dir, type, Optional.empty(), project.getResourceName());
            setupResource(resource);
            project.addResource(resource);
        } else {
            SwingUtilities.invokeLater(() -> showAddLocaleDialog());
        }
        translationTree.setModel(new TranslationTreeModel());

        updateHistory();
        updateUI();
        requestFocusInFirstResourceField();
    } catch (IOException e) {
        log.error("Error creating resource files", e);
        showError(MessageBundle.get("resources.create.error"));
    }
}

From source file:fr.insalyon.creatis.vip.vipcoworkapplet.Cowork.java

/** Initializes the applet Main */
@Override//  w w w  .  j  a v a2s.c  om
public void init() {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Cowork.class.getName()).log(java.util.logging.Level.SEVERE, null,
                ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Cowork.class.getName()).log(java.util.logging.Level.SEVERE, null,
                ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Cowork.class.getName()).log(java.util.logging.Level.SEVERE, null,
                ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Cowork.class.getName()).log(java.util.logging.Level.SEVERE, null,
                ex);
    }
    //</editor-fold>

    /* Create and display the applet */
    try {
        java.awt.EventQueue.invokeAndWait(new Runnable() {

            public void run() {
                try {
                    sessionId = getParameter("sessionId");
                    email = getParameter("email");
                    endpoint = getCodeBase().toString() + "/fr.insalyon.creatis.vip.portal.Main/coworkservice";

                    DesignFrame frame = new DesignFrame(true);
                    frame.setAppletParams(endpoint, email, sessionId);

                    String home = System.getProperty("user.home");
                    File config = new File(home + File.separator + ".cowork/config");
                    PropertiesConfiguration pc = new PropertiesConfiguration(config);

                    String password = (String) pc.getProperty("password"),
                            login = (String) pc.getProperty("login");
                    PasswordDialog p = new PasswordDialog(null, "Please login to the knowledge base");
                    while (password == null || login == null) {
                        if (p.showDialog()) {

                            login = p.getName();
                            password = p.getPass();
                        }
                        if (login != null && password != null) {
                            if (JOptionPane.showConfirmDialog(null, "Remember credentials (unencrypted)?",
                                    "Rememeber?", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                                pc.setProperty("password", password);
                                pc.setProperty("login", login);
                                pc.save();
                            }
                        }

                    }

                    KnowledgeBase kb = new KnowledgeBase("jdbc:mysql://" + getCodeBase().getHost() + "/cowork",
                            login, password, "http://cowork.i3s.cnrs.fr/");
                    frame.setKB(kb);
                    frame.setVisible(true);
                } catch (ConfigurationException ex) {
                    ex.printStackTrace();

                    JOptionPane.showMessageDialog(null, ExceptionUtils.getStackTrace(ex), "Error",
                            JOptionPane.ERROR_MESSAGE);
                } catch (SQLException ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(null, ExceptionUtils.getStackTrace(ex), "Error",
                            JOptionPane.ERROR_MESSAGE);
                }

            }
        });
    } catch (Exception ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, ExceptionUtils.getStackTrace(ex), "Error",
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:VoteDialog.java

private JPanel createSimpleDialogBox() {
    final int numButtons = 4;
    JRadioButton[] radioButtons = new JRadioButton[numButtons];

    final ButtonGroup group = new ButtonGroup();

    JButton voteButton = null;/*from ww  w . j a va 2 s . c  o  m*/

    final String defaultMessageCommand = "default";
    final String yesNoCommand = "yesno";
    final String yeahNahCommand = "yeahnah";
    final String yncCommand = "ync";

    radioButtons[0] = new JRadioButton("<html>Candidate 1: <font color=red>Sparky the Dog</font></html>");
    radioButtons[0].setActionCommand(defaultMessageCommand);

    radioButtons[1] = new JRadioButton("<html>Candidate 2: <font color=green>Shady Sadie</font></html>");
    radioButtons[1].setActionCommand(yesNoCommand);

    radioButtons[2] = new JRadioButton("<html>Candidate 3: <font color=blue>R.I.P. McDaniels</font></html>");
    radioButtons[2].setActionCommand(yeahNahCommand);

    radioButtons[3] = new JRadioButton(
            "<html>Candidate 4: <font color=maroon>Duke the Java<font size=-2><sup>TM</sup></font size> Platform Mascot</font></html>");
    radioButtons[3].setActionCommand(yncCommand);

    for (int i = 0; i < numButtons; i++) {
        group.add(radioButtons[i]);
    }
    // Select the first button by default.
    radioButtons[0].setSelected(true);

    voteButton = new JButton("Vote");

    voteButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String command = group.getSelection().getActionCommand();

            // ok dialog
            if (command == defaultMessageCommand) {
                JOptionPane.showMessageDialog(frame, "This candidate is a dog. Invalid vote.");

                // yes/no dialog
            } else if (command == yesNoCommand) {
                int n = JOptionPane.showConfirmDialog(frame,
                        "This candidate is a convicted felon. \nDo you still want to vote for her?",
                        "A Follow-up Question", JOptionPane.YES_NO_OPTION);
                if (n == JOptionPane.YES_OPTION) {
                    setLabel("OK. Keep an eye on your wallet.");
                } else if (n == JOptionPane.NO_OPTION) {
                    setLabel("Whew! Good choice.");
                } else {
                    setLabel("It is your civic duty to cast your vote.");
                }

                // yes/no (with customized wording)
            } else if (command == yeahNahCommand) {
                Object[] options = { "Yes, please", "No, thanks" };
                int n = JOptionPane.showOptionDialog(frame,
                        "This candidate is deceased. \nDo you still want to vote for him?",
                        "A Follow-up Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
                        options, options[0]);
                if (n == JOptionPane.YES_OPTION) {
                    setLabel("I hope you don't expect much from your candidate.");
                } else if (n == JOptionPane.NO_OPTION) {
                    setLabel("Whew! Good choice.");
                } else {
                    setLabel("It is your civic duty to cast your vote.");
                }

                // yes/no/cancel (with customized wording)
            } else if (command == yncCommand) {
                Object[] options = { "Yes!", "No, I'll pass", "Well, if I must" };
                int n = JOptionPane.showOptionDialog(frame,
                        "Duke is a cartoon mascot. \nDo you  " + "still want to cast your vote?",
                        "A Follow-up Question", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
                        null, options, options[2]);
                if (n == JOptionPane.YES_OPTION) {
                    setLabel("Excellent choice.");
                } else if (n == JOptionPane.NO_OPTION) {
                    setLabel("Whatever you say. It's your vote.");
                } else if (n == JOptionPane.CANCEL_OPTION) {
                    setLabel("Well, I'm certainly not going to make you vote.");
                } else {
                    setLabel("It is your civic duty to cast your vote.");
                }
            }
            return;
        }
    });
    System.out.println("calling createPane");
    return createPane(simpleDialogDesc + ":", radioButtons, voteButton);
}

From source file:me.childintime.childintime.InitialSetup.java

/**
 * Clean and refresh the application environment for developers.
 * This deletes all application files and configurations from previous versions.
 * This ensures that a fresh application instance is used for development.
 *///from   w  w w  . ja v a 2  s  . c  o m
private void cleanApplicationEnvironment() {
    // Show a status message
    this.progressDialog.setStatus("Confirming environment cleanup...");

    // Make sure the clean environment feature is enabled
    if (!App.APP_CLEAN_ENVIRONMENT)
        return;

    // Show a warning
    if (!Arrays.asList(Core.getInstance().getStarupArgs()).contains(FLAG_HIDE_CLEAN_ENVIRONMENT_WARNING)) {
        // Create a list with the buttons to show in the option dialog
        List<String> buttons = new ArrayList<>();
        buttons.add("Clean Environment");
        buttons.add("Keep Environment");

        // Reverse the button list if we're on a Mac OS X system
        if (Platform.isMacOsX())
            Collections.reverse(buttons);

        // Show the option dialog
        final int option = JOptionPane.showOptionDialog(this.progressDialog,
                "The developer option Clean Environment is enabled.\n\n"
                        + "Would you like to clean your application environment?\n\n"
                        + "Cleaning the environment will delete all previous application files and configurations,\n"
                        + "to ensure that you're using a fresh application instance for development.\n\n"
                        + "This feature must be disabled in production.",
                App.APP_NAME + " - Developer mode - Environment cleanup", JOptionPane.YES_NO_OPTION,
                JOptionPane.WARNING_MESSAGE, null, buttons.toArray(),
                buttons.get(!Platform.isMacOsX() ? 0 : 1));

        // Make sure the clean option is pressed
        if (option != (!Platform.isMacOsX() ? 0 : 1))
            return;
    }

    // Show a status message
    this.progressDialog.setStatus("Refreshing application environment...");

    // Delete the application directory
    try {
        if (App.getDirectory().exists())
            FileUtils.deleteDirectory(App.getDirectory());

    } catch (IOException e) {
        showError("Failed to refresh application environment.");
        e.printStackTrace();
    }
}

From source file:calendarexportplugin.exporter.GoogleExporter.java

public boolean exportPrograms(Program[] programs, CalendarExportSettings settings,
        AbstractPluginProgramFormating formatting) {
    try {// w ww .  j ava 2  s .com
        boolean uploadedItems = false;
        mPassword = IOUtilities.xorDecode(settings.getExporterProperty(PASSWORD), 345903).trim();

        if (!settings.getExporterProperty(STORE_PASSWORD, false)) {
            if (!showLoginDialog(settings)) {
                return false;
            }
        }

        if (!settings.getExporterProperty(STORE_SETTINGS, false)) {
            if (!showCalendarSettings(settings)) {
                return false;
            }
        }

        GoogleService myService = new GoogleService("cl", "tvbrowser-tvbrowsercalenderplugin-"
                + CalendarExportPlugin.getInstance().getInfo().getVersion().toString());
        myService.setUserCredentials(settings.getExporterProperty(USERNAME).trim(), mPassword);

        URL postUrl = new URL("http://www.google.com/calendar/feeds/"
                + settings.getExporterProperty(SELECTED_CALENDAR) + "/private/full");

        SimpleDateFormat formatDay = new SimpleDateFormat("yyyy-MM-dd");
        formatDay.setTimeZone(TimeZone.getTimeZone("GMT"));
        SimpleDateFormat formatTime = new SimpleDateFormat("HH:mm:ss");
        formatTime.setTimeZone(TimeZone.getTimeZone("GMT"));

        ParamParser parser = new ParamParser();
        for (Program program : programs) {
            final String title = parser.analyse(formatting.getTitleValue(), program);

            // First step: search for event in calendar
            boolean createEvent = true;

            CalendarEventEntry entry = findEntryForProgram(myService, postUrl, title, program);

            if (entry != null) {
                int ret = JOptionPane.showConfirmDialog(null,
                        mLocalizer.msg("alreadyAvailable", "already available", program.getTitle()),
                        mLocalizer.msg("title", "Add event?"), JOptionPane.YES_NO_OPTION,
                        JOptionPane.QUESTION_MESSAGE);

                if (ret != JOptionPane.YES_OPTION) {
                    createEvent = false;
                }
            }

            // add event to calendar
            if (createEvent) {
                EventEntry myEntry = new EventEntry();

                myEntry.setTitle(new PlainTextConstruct(title));

                String desc = parser.analyse(formatting.getContentValue(), program);
                myEntry.setContent(new PlainTextConstruct(desc));

                Calendar c = CalendarToolbox.getStartAsCalendar(program);

                DateTime startTime = new DateTime(c.getTime(), c.getTimeZone());

                c = CalendarToolbox.getEndAsCalendar(program);

                DateTime endTime = new DateTime(c.getTime(), c.getTimeZone());

                When eventTimes = new When();

                eventTimes.setStartTime(startTime);
                eventTimes.setEndTime(endTime);

                myEntry.addTime(eventTimes);

                if (settings.getExporterProperty(REMINDER, false)) {
                    int reminderMinutes = 0;

                    try {
                        reminderMinutes = settings.getExporterProperty(REMINDER_MINUTES, 0);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }

                    if (settings.getExporterProperty(REMINDER_ALERT, false)) {
                        addReminder(myEntry, reminderMinutes, Reminder.Method.ALERT);
                    }

                    if (settings.getExporterProperty(REMINDER_EMAIL, false)) {
                        addReminder(myEntry, reminderMinutes, Reminder.Method.EMAIL);
                    }

                    if (settings.getExporterProperty(REMINDER_SMS, false)) {
                        addReminder(myEntry, reminderMinutes, Reminder.Method.SMS);
                    }

                }

                if (settings.isShowBusy()) {
                    myEntry.setTransparency(BaseEventEntry.Transparency.OPAQUE);
                } else {
                    myEntry.setTransparency(BaseEventEntry.Transparency.TRANSPARENT);
                }
                // Send the request and receive the response:
                myService.insert(postUrl, myEntry);
                uploadedItems = true;
            }
        }

        if (uploadedItems) {
            JOptionPane.showMessageDialog(CalendarExportPlugin.getInstance().getBestParentFrame(),
                    mLocalizer.msg("exportDone", "Google Export done."), mLocalizer.msg("export", "Export"),
                    JOptionPane.INFORMATION_MESSAGE);
        }

        return true;
    } catch (AuthenticationException e) {
        ErrorHandler.handle(mLocalizer.msg("loginFailure",
                "Problems during login to Service.\nMaybe bad username or password?"), e);
        settings.setExporterProperty(STORE_PASSWORD, false);
    } catch (Exception e) {
        ErrorHandler.handle(mLocalizer.msg("commError", "Error while communicating with Google!"), e);
    }

    return false;
}

From source file:InternalFrameTest.java

/**
 * Creates an internal frame on the desktop.
 * @param c the component to display in the internal frame
 * @param t the title of the internal frame.
 *///from ww  w. ja v a2s .com
public void createInternalFrame(Component c, String t) {
    final JInternalFrame iframe = new JInternalFrame(t, true, // resizable
            true, // closable
            true, // maximizable
            true); // iconifiable

    iframe.add(c, BorderLayout.CENTER);
    desktop.add(iframe);

    iframe.setFrameIcon(new ImageIcon("document.gif"));

    // add listener to confirm frame closing
    iframe.addVetoableChangeListener(new VetoableChangeListener() {
        public void vetoableChange(PropertyChangeEvent event) throws PropertyVetoException {
            String name = event.getPropertyName();
            Object value = event.getNewValue();

            // we only want to check attempts to close a frame
            if (name.equals("closed") && value.equals(true)) {
                // ask user if it is ok to close
                int result = JOptionPane.showInternalConfirmDialog(iframe, "OK to close?", "Select an Option",
                        JOptionPane.YES_NO_OPTION);

                // if the user doesn't agree, veto the close
                if (result != JOptionPane.YES_OPTION)
                    throw new PropertyVetoException("User canceled close", event);
            }
        }
    });

    // position frame
    int width = desktop.getWidth() / 2;
    int height = desktop.getHeight() / 2;
    iframe.reshape(nextFrameX, nextFrameY, width, height);

    iframe.show();

    // select the frame--might be vetoed
    try {
        iframe.setSelected(true);
    } catch (PropertyVetoException e) {
    }

    frameDistance = iframe.getHeight() - iframe.getContentPane().getHeight();

    // compute placement for next frame

    nextFrameX += frameDistance;
    nextFrameY += frameDistance;
    if (nextFrameX + width > desktop.getWidth())
        nextFrameX = 0;
    if (nextFrameY + height > desktop.getHeight())
        nextFrameY = 0;
}

From source file:net.sf.keystore_explorer.gui.CreateApplicationGui.java

private void checkCaCerts(final KseFrame kseFrame) {

    File caCertificatesFile = applicationSettings.getCaCertificatesFile();

    if (caCertificatesFile.exists()) {
        return;/*from  ww w .  j a  v  a 2 s  .  c  om*/
    }

    // cacerts file is not where we expected it => detect location and inform user
    final File newCaCertsFile = new File(AuthorityCertificates.getDefaultCaCertificatesLocation().toString());

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            int selected = JOptionPane.showConfirmDialog(kseFrame.getUnderlyingFrame(), MessageFormat
                    .format(res.getString("CreateApplicationGui.CaCertsFileNotFound.message"), newCaCertsFile),
                    KSE.getApplicationName(), JOptionPane.YES_NO_OPTION);

            if (selected == JOptionPane.YES_OPTION) {
                applicationSettings.setCaCertificatesFile(newCaCertsFile);
            }
        }
    });
}

From source file:com.sshtools.shift.FileTransferDialog.java

/**
 * Creates a new FileTransferDialog object.
 *
 * @param frame//from   w  ww .  j av  a  2s  .  co m
 * @param title
 * @param fileCount
 */

/*public FileTransferDialog(Frame frame, String title) {
  this(frame, title, op.getNewFiles().size()
               + op.getUpdatedFiles().size());
  this.op = op;
   }*/

public FileTransferDialog(Frame frame, String title, int fileCount) {

    super("0% Complete - " + title);

    this.setIconImage(ShiftSessionPanel.FILE_BROWSER_ICON.getImage());

    this.title = title;

    try {

        jbInit();

        pack();

    }

    catch (Exception ex) {

        ex.printStackTrace();

    }

    this.addWindowListener(new WindowAdapter() {

        public void windowClosing(WindowEvent e) {

            if (cancelled || completed) {

                setVisible(false);

            }

            else {

                if (JOptionPane.showConfirmDialog(FileTransferDialog.this,

                        "Cancel the file operation(s)?",

                        "Close Window",

                        JOptionPane.YES_NO_OPTION,

                        JOptionPane.ERROR_MESSAGE) ==

                JOptionPane.YES_OPTION) {

                    cancelOperation();

                    hide();

                }

            }

        }

    });

}

From source file:com.net2plan.gui.GUINet2Plan.java

private static void askForClose() {
    int result = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit Net2Plan?",
            "Exit from Net2Plan", JOptionPane.YES_NO_OPTION);

    if (result == JOptionPane.YES_OPTION)
        System.exit(0);// w w  w  .  j a  v  a2 s. c o m
}

From source file:br.org.acessobrasil.silvinha.util.versoes.AtualizadorDeVersoes.java

public boolean baixarVersao() {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    NameValuePair param = new NameValuePair("param", "update");
    method.setRequestBody(new NameValuePair[] { param });
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    JFrame down = new JFrame("Download");
    File downFile = null;/*from w  w  w  . java 2  s  . c  o m*/
    InputStream is = null;
    FileOutputStream fos = null;
    try {
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            log.error("Method failed: " + method.getStatusLine());
        }
        Header header = method.getResponseHeader("Content-Disposition");
        String fileName = "silvinha.exe";
        if (header != null) {
            fileName = header.getValue().split("=")[1];
        }
        // Read the response body.
        is = method.getResponseBodyAsStream();
        down.pack();
        ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(down,
                TradAtualizadorDeVersoes.FAZ_DOWNLOAD_FILE + fileName, is);
        pmis.getProgressMonitor().setMinimum(0);
        pmis.getProgressMonitor().setMaximum((int) method.getResponseContentLength());
        downFile = new File(fileName);
        fos = new FileOutputStream(downFile);
        int c;
        while (((c = pmis.read()) != -1) && (!pmis.getProgressMonitor().isCanceled())) {
            fos.write(c);
        }
        fos.flush();
        fos.close();
        String msgOK = TradAtualizadorDeVersoes.DOWNLOAD_EXITO
                + TradAtualizadorDeVersoes.DESEJA_ATUALIZAR_EXECUTAR + TradAtualizadorDeVersoes.ARQUIVO_DE_NOME
                + fileName + TradAtualizadorDeVersoes.LOCALIZADO_NA + TradAtualizadorDeVersoes.PASTA_INSTALACAO
                + TradAtualizadorDeVersoes.APLICACAO_DEVE_SER_ENCERRADA
                + TradAtualizadorDeVersoes.DESEJA_CONTINUAR_ATUALIZACAO;
        if (JOptionPane.showConfirmDialog(null, msgOK, TradAtualizadorDeVersoes.ATUALIZACAO_DO_PROGRAMA,
                JOptionPane.YES_NO_OPTION) == 0) {
            return true;
        } else {
            return false;
        }
    } catch (HttpException he) {
        log.error("Fatal protocol violation: " + he.getMessage(), he);
        return false;
    } catch (InterruptedIOException iioe) {
        method.abort();
        String msg = GERAL.OP_CANCELADA_USUARIO + TradAtualizadorDeVersoes.DIRECIONADO_A_APLICACAO;
        JOptionPane.showMessageDialog(down, msg);
        try {
            if (fos != null) {
                fos.close();
            }
        } catch (IOException ioe) {
            method.releaseConnection();
            System.exit(0);
        }
        if (downFile != null && downFile.exists()) {
            downFile.delete();
        }
        return false;
        //         System.err.println("Fatal transport error: " + iioe.getMessage());
        //         iioe.printStackTrace();
    } catch (IOException ioe) {
        log.error("Fatal transport error: " + ioe.getMessage(), ioe);
        return false;
    } finally {
        //Release the connection.
        method.releaseConnection();
    }
}