Example usage for javax.swing JOptionPane YES_OPTION

List of usage examples for javax.swing JOptionPane YES_OPTION

Introduction

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

Prototype

int YES_OPTION

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

Click Source Link

Document

Return value from class method if YES is chosen.

Usage

From source file:com.googlecode.onevre.utils.ServerClassLoader.java

private boolean verifyCertificate(X509Certificate cert) {
    try {//  w  w  w  . j ava2 s .  c om
        String keypass = "";
        String keystorename = System.getProperty("deployment.user.security.trusted.certs");
        if (keystorename == null) {
            throw new IOException("No trusted certs keystore");
        }

        KeyStore keystore = KeyStore.getInstance("JKS", "SUN");
        File file = new File(keystorename);
        if (!file.exists()) {
            keystore.load(null, keypass.toCharArray());
        } else {
            keystore.load(new FileInputStream(keystorename), keypass.toCharArray());
        }
        boolean isInStore = false;
        Enumeration<String> aliases = keystore.aliases();
        while (aliases.hasMoreElements() && !isInStore) {
            String alias = aliases.nextElement();
            Certificate certificate = keystore.getCertificate(alias);
            if (certificate != null) {
                if (certificate.equals(cert)) {
                    isInStore = true;
                }
            }
        }
        if (!isInStore) {
            int result = JOptionPane.showConfirmDialog(null,
                    "Do you want to trust the bridge implementation " + "signed by\n"
                            + cert.getSubjectX500Principal().getName(),
                    "Trust source?", JOptionPane.YES_NO_OPTION);
            if (result == JOptionPane.YES_OPTION) {
                keystore.setEntry("deploymentusercert-" + System.currentTimeMillis(),
                        new KeyStore.TrustedCertificateEntry(cert), null);
                FileOutputStream output = new FileOutputStream(keystorename);
                keystore.store(output, keypass.toCharArray());
                output.close();
                return true;
            }
            return false;
        }
        return true;
    } catch (Throwable t) {
        t.printStackTrace();
    }
    return false;
}

From source file:gdt.jgui.entity.bonddetail.JBondDetailPanel.java

/**
 * Get the context menu.// w  w  w .java 2s .c o m
 * @return the context menu.
 */
@Override
public JMenu getContextMenu() {

    menu1 = new JMenu("Context");
    menu1.addMenuListener(new MenuListener() {
        @Override
        public void menuSelected(MenuEvent e) {
            //   System.out.println("JBondDetailPanel:getConextMenu:BEGIN");
            menu1.removeAll();
            JMenuItem selectItem = new JMenuItem("Select all");
            selectItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JItemPanel[] ipa = getItems();
                    if (ipa != null) {
                        for (JItemPanel ip : ipa)
                            ip.setChecked(true);
                    }
                }
            });
            menu1.add(selectItem);
            JMenuItem unselectItem = new JMenuItem("Unselect all");
            unselectItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JItemPanel[] ipa = getItems();
                    if (ipa != null) {
                        for (JItemPanel ip : ipa)
                            ip.setChecked(false);
                    }
                }
            });
            menu1.addSeparator();
            JMenuItem doneItem = new JMenuItem("Done");
            doneItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (requesterResponseLocator$ != null) {
                        try {
                            byte[] ba = Base64.decodeBase64(requesterResponseLocator$);
                            String responseLocator$ = new String(ba, "UTF-8");
                            JConsoleHandler.execute(console, responseLocator$);
                        } catch (Exception ee) {
                            LOGGER.severe(ee.toString());
                        }
                    } else
                        console.back();

                }

            });
            menu1.add(doneItem);
            menu1.addSeparator();
            addItem = new JMenuItem("Add");
            addItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        Entigrator entigrator = console.getEntigrator(entihome$);

                        JContext adp = (JContext) ExtensionHandler.loadHandlerInstance(entigrator,
                                BondDetailHandler.EXTENSION_KEY, "gdt.jgui.entity.bonddetail.JAddDetailPanel");
                        String adpLocator$ = adp.getLocator();
                        adpLocator$ = Locator.append(adpLocator$, Entigrator.ENTIHOME, entihome$);
                        adpLocator$ = Locator.append(adpLocator$, EntityHandler.ENTITY_KEY, entityKey$);
                        JConsoleHandler.execute(console, adpLocator$);

                    } catch (Exception ee) {
                        LOGGER.severe(ee.toString());
                    }
                }
            });
            menu1.add(addItem);
            if (hasToPaste()) {
                JMenuItem pasteItem = new JMenuItem("Paste");
                pasteItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        paste();

                    }
                });
                menu1.add(pasteItem);
            }
            if (hasSelectedItems()) {
                JMenuItem deleteItem = new JMenuItem("Delete");
                deleteItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        int response = JOptionPane.showConfirmDialog(console.getContentPanel(), "Delete ?",
                                "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                        if (response == JOptionPane.YES_OPTION) {

                            delete();
                            JBondDetailPanel bdp = new JBondDetailPanel();
                            String bdpLocator$ = bdp.getLocator();
                            bdpLocator$ = Locator.append(bdpLocator$, Entigrator.ENTIHOME, entihome$);
                            bdpLocator$ = Locator.append(bdpLocator$, EntityHandler.ENTITY_KEY, entityKey$);
                            bdpLocator$ = Locator.append(bdpLocator$, JBondsPanel.BOND_KEY, bondKey$);
                            JConsoleHandler.execute(console, bdpLocator$);
                        }
                    }
                });
                menu1.add(deleteItem);
            }

        }

        @Override
        public void menuDeselected(MenuEvent e) {
        }

        @Override
        public void menuCanceled(MenuEvent e) {
        }
    });
    return menu1;
}

From source file:com.floreantpos.bo.ui.explorer.QuickMaintenanceExplorer.java

private static void quickMaintainShopTable(ShopTable shopTable) {
    try {//  w  w w  . j a v  a2s . co m
        if (shopTable.getId() != null) {
            if (btnCopy.isSelected()) {
                ShopTable newShopTable = new ShopTable();
                PropertyUtils.copyProperties(newShopTable, shopTable);
                newShopTable.setId(shopTable.getId() + 1);
                newShopTable.setDescription(String.valueOf(shopTable.getId() + 1));
                shopTable = newShopTable;
            } else if (btnDelete.isSelected()) {
                if (POSMessageDialog.showYesNoQuestionDialog(POSUtil.getFocusedWindow(),
                        POSConstants.CONFIRM_DELETE, POSConstants.DELETE) != JOptionPane.YES_OPTION) {
                    return;
                }

                ShopTableDAO shopTableDAO = new ShopTableDAO();
                shopTableDAO.delete(shopTable.getId());
                TableMapView.getInstance().updateView();
                return;
            }
        }
        ShopTableForm editor = new ShopTableForm();
        editor.setBean(shopTable);
        BeanEditorDialog dialog = new BeanEditorDialog(Application.getPosWindow(), editor);
        dialog.open(600, 500);
        if (dialog.isCanceled())
            return;
        TableMapView.getInstance().updateView();
        return;
    } catch (Exception e) {
        return;
    }
}

From source file:edu.mit.fss.examples.member.gui.CommSubsystemPanel.java

/**
 * Exports this panel's connectivity dataset.
 *//*ww  w  .j  a va 2 s.  c  o  m*/
private void exportDataset() {
    if (JFileChooser.APPROVE_OPTION == fileChooser.showSaveDialog(this)) {
        File f = fileChooser.getSelectedFile();

        if (!f.exists() || JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this,
                "Overwrite existing file " + f.getName() + "?", "File Exists", JOptionPane.YES_NO_OPTION)) {
            logger.info("Exporting dataset to file " + f.getPath() + ".");
            try {
                BufferedWriter bw = Files.newBufferedWriter(Paths.get(f.getPath()), Charset.defaultCharset());

                StringBuilder b = new StringBuilder();

                // synchronize on map for thread safety
                synchronized (connectSeriesMap) {
                    for (Transmitter tx : connectSeriesMap.keySet()) {
                        TimeSeries s = connectSeriesMap.get(tx);
                        b.append(tx.getName()).append(" Connectivity\n").append("Time, Value\n");
                        for (int j = 0; j < s.getItemCount(); j++) {
                            b.append(s.getTimePeriod(j).getStart().getTime()).append(", ").append(s.getValue(j))
                                    .append("\n");
                        }
                    }
                }

                bw.write(b.toString());
                bw.close();
            } catch (IOException e) {
                logger.error(e);
            }
        }
    }
}

From source file:com.compomics.colims.client.controller.AnalyticalRunsSearchSettingsController.java

/**
 * Delete the database entity (project, experiment, analytical runs) from
 * the database. Shows a confirmation dialog first. When confirmed, a
 * DeleteDbTask message is sent to the DB task queue. A message dialog is
 * shown in case the queue cannot be reached or in case of an IOException
 * thrown by the sendDbTask method./*from   ww w  .  j  a  v a2  s .  co  m*/
 *
 * @param entity the entity to delete
 * @param dbEntityClass the database entity class
 * @return true if the delete task is confirmed.
 */
private boolean deleteEntity(final DatabaseEntity entity, final Class dbEntityClass) {
    boolean deleteConfirmation = false;

    //check delete permissions
    if (userBean.getDefaultPermissions().get(DefaultPermission.DELETE)) {
        int option = JOptionPane.showConfirmDialog(mainController.getMainFrame(),
                "Are you sure? This will remove all underlying database relations (spectra, psm's, ...) as well."
                        + System.lineSeparator() + "A delete task will be sent to the database task queue.",
                "Delete " + dbEntityClass.getSimpleName() + " confirmation.", JOptionPane.YES_NO_OPTION);
        if (option == JOptionPane.YES_OPTION) {
            //check connection
            if (queueManager.isReachable()) {
                DeleteDbTask deleteDbTask = new DeleteDbTask(dbEntityClass, entity.getId(),
                        userBean.getCurrentUser().getId());
                try {
                    dbTaskProducer.sendDbTask(deleteDbTask);
                    deleteConfirmation = true;
                } catch (IOException e) {
                    LOGGER.error(e, e.getCause());
                    eventBus.post(new UnexpectedErrorMessageEvent(e.getMessage()));
                }
            } else {
                eventBus.post(new StorageQueuesConnectionErrorMessageEvent(queueManager.getBrokerName(),
                        queueManager.getBrokerUrl(), queueManager.getBrokerJmxUrl()));
            }
        }
    } else {
        mainController.showPermissionErrorDialog(
                "Your user doesn't have rights to delete this " + entity.getClass().getSimpleName());
    }

    return deleteConfirmation;
}

From source file:net.sf.jabref.gui.openoffice.StyleSelectDialog.java

private void setupPopupMenu() {
    popup.add(edit);//from   www  . j av  a2  s .  c o m
    popup.add(show);
    popup.add(remove);
    popup.add(reload);

    // Add action listener to "Edit" menu item, which is supposed to open the style file in an external editor:
    edit.addActionListener(actionEvent -> getSelectedStyle().ifPresent(style -> {
        Optional<ExternalFileType> type = ExternalFileTypes.getInstance().getExternalFileTypeByExt("jstyle");
        String link = style.getPath();
        try {
            if (type.isPresent()) {
                JabRefDesktop.openExternalFileAnyFormat(new BibDatabaseContext(), link, type);
            } else {
                JabRefDesktop.openExternalFileUnknown(frame, new BibEntry(), new BibDatabaseContext(), link,
                        new UnknownExternalFileType("jstyle"));
            }
        } catch (IOException e) {
            LOGGER.warn("Problem open style file editor", e);
        }
    }));

    // Add action listener to "Show" menu item, which is supposed to open the style file in a dialog:
    show.addActionListener(actionEvent -> getSelectedStyle().ifPresent(this::displayStyle));

    // Create action listener for removing a style, also used for the remove button
    removeAction = actionEvent -> getSelectedStyle().ifPresent(style -> {
        if (!style.isFromResource() && (JOptionPane.showConfirmDialog(diag,
                Localization.lang("Are you sure you want to remove the style?"),
                Localization.lang("Remove style"), JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)) {
            if (!loader.removeStyle(style)) {
                LOGGER.info("Problem removing style");
            }
            updateStyles();
        }
    });
    // Add it to the remove menu item
    remove.addActionListener(removeAction);

    // Add action listener to the "Reload" menu item, which is supposed to reload an external style file
    reload.addActionListener(actionEvent -> getSelectedStyle().ifPresent(style -> {
        try {
            style.ensureUpToDate();
        } catch (IOException e) {
            LOGGER.warn("Problem with style file '" + style.getPath() + "'", e);
        }
    }));

}

From source file:com.konifar.material_icon_generator.MaterialDesignIconGenerateDialog.java

@Override
protected void doOKAction() {
    if (model == null)
        return;/* w w  w . jav a 2 s .c om*/

    if (!isConfirmed())
        return;

    if (alreadyFileExists()) {
        final int option = JOptionPane.showConfirmDialog(panelMain, "File already exists, overwrite this ?",
                "File exists", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
                new ImageIcon(getClass().getResource(ICON_WARNING)));

        if (option == JOptionPane.YES_OPTION) {
            create();
        }
    } else {
        create();
    }

}

From source file:edu.ku.brc.af.ui.db.JAutoCompTextField.java

/**
 * It may or may not ask if it can add, and then it adds the new item.
 * @param strArg the string that is to be added
 * @return whether it was added/*from ww w  . ja va2s.c  o  m*/
 */
protected boolean askToAdd(String strArg) {

    if (ignoreFocus) {
        return false;
    }

    if (hasChanged && isNotEmpty(strArg)) {
        ignoreFocus = true;
        String msg = UIRegistry.getLocalizedMessage("JAutoCompTextField.REMEM_VAL", strArg); //$NON-NLS-1$
        if (!askBeforeSave || JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this, msg,
                UIRegistry.getResourceString("JAutoCompTextField.REMEM_VAL_TITLE"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                JOptionPane.YES_NO_OPTION)) {
            if (dbAdapter != null) {
                dbAdapter.addItem(strArg, null);
            }
            hasChanged = false;
            ignoreFocus = false;
            return true;
        }
        ignoreFocus = false;
    }
    return false;
}

From source file:edu.ku.brc.specify.dbsupport.TaskSemaphoreMgr.java

/**
 * @param title//from   w ww  .j a  va  2 s . c o m
 * @param name
 * @param scope
 * @return
 */
public static boolean askUserToUnlock(final String title, final String name, final SCOPE scope) {
    SpecifyUser user = AppContextMgr.getInstance().getClassObject(SpecifyUser.class);
    Discipline discipline = scope == SCOPE.Discipline
            ? AppContextMgr.getInstance().getClassObject(Discipline.class)
            : null;
    Collection collection = scope == SCOPE.Collection
            ? AppContextMgr.getInstance().getClassObject(Collection.class)
            : null;

    DataProviderSessionIFace session = null;
    try {
        session = DataProviderFactory.getInstance().createSession();

        SpTaskSemaphore semaphore = null;
        try {
            semaphore = getSemaphore(session, name, scope, discipline, collection);

        } catch (StaleObjectException ex) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(TaskSemaphoreMgr.class, ex);
            semaphore = null;
        }

        if (semaphore == null) {
            // can't be unlocked at this time.
            // or it isn't locked

        } else {
            if (!semaphore.getIsLocked()
                    && !(semaphore.getUsageCount() != null && semaphore.getUsageCount() > 0)) {
                return false;
            }

            // Check to see if we have the same user on the same machine.
            String currMachineName = InetAddress.getLocalHost().toString();
            String dbMachineName = semaphore.getMachineName();

            if (StringUtils.isNotEmpty(dbMachineName) && StringUtils.isNotEmpty(currMachineName)
                    && currMachineName.equals(dbMachineName) && semaphore.getOwner() != null && user != null
                    && user.getId().equals(semaphore.getOwner().getId())) {
                // In use by this user

                int options = JOptionPane.YES_NO_OPTION;
                Object[] optionLabels = new String[] { getResourceString("SpTaskSemaphore.OVERRIDE"), //$NON-NLS-1$
                        getResourceString("CANCEL")//$NON-NLS-1$
                };
                int userChoice = JOptionPane.showOptionDialog(UIRegistry.getTopWindow(),
                        getLocalizedMessage("SpTaskSemaphore.IN_USE_BY_YOU_UNLK", title, title),
                        getResourceString("SpTaskSemaphore.IN_USE_TITLE"), //$NON-NLS-1$
                        options, JOptionPane.QUESTION_MESSAGE, null, optionLabels, 1);

                return userChoice == JOptionPane.YES_OPTION;
            }

            String userStr = prevLockedBy != null ? prevLockedBy : semaphore.getOwner().getIdentityTitle();
            String msg = UIRegistry.getLocalizedMessage("SpTaskSemaphore.IN_USE_OV_UNLK", title, userStr,
                    semaphore.getLockedTime() == null ? "?" : semaphore.getLockedTime().toString());

            int options;
            Object[] optionLabels;
            options = JOptionPane.YES_NO_OPTION;
            optionLabels = new String[] { getResourceString("SpTaskSemaphore.OVERRIDE"), //$NON-NLS-1$
                    getResourceString("CANCEL"), //$NON-NLS-1$
            };

            int userChoice = JOptionPane.showOptionDialog(UIRegistry.getTopWindow(), msg,
                    getResourceString("SpTaskSemaphore.IN_USE_TITLE"), //$NON-NLS-1$
                    options, JOptionPane.QUESTION_MESSAGE, null, optionLabels, 1);
            return userChoice == JOptionPane.YES_OPTION;
        }

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(TaskSemaphoreMgr.class, ex);
        ex.printStackTrace();
        //log.error(ex);

    } finally {
        if (session != null) {
            session.close();
        }
    }

    return false;
}

From source file:de.mpg.mpi_inf.bioinf.netanalyzer.ui.ChartDisplayPanel.java

/**
 * Handles the pressing of the {@link #btnFilter} button.
 * <p>//from   w  w w  . j av  a 2 s .  co m
 * After asking the user for confirmation, this method adds or removes filter to the complex
 * parameter displayed.
 * </p>
 */
private void performFilter() {
    if (originalParam == visualizer.getComplexParam()) {
        // Create filter
        try {
            final Class<?> paramClass = originalParam.getClass();
            final Class<?> filterClass = Plugin.getFilterDialogClass(paramClass);
            final Constructor<?> constr = filterClass.getConstructors()[0];
            Object[] cParams = new Object[] { ownerDialog, Messages.DT_FILTERDATA, originalParam,
                    visualizer.getSettings() };
            ComplexParamFilterDialog d = (ComplexParamFilterDialog) constr.newInstance(cParams);
            ComplexParamFilter filter = d.showDialog();
            if (filter != null) {
                btnFilter.setText(Messages.DI_REMOVEFILTER);
                btnFilter.setToolTipText(Messages.TT_REMOVEFILTER);
                visualizer.setComplexParam(filter.filter(originalParam));
                chart = visualizer.createControl();
                JFreeChartConn.setChart(chartPanel, chart);
            }
        } catch (InnerException ex) {
            // NetworkAnalyzer internal error
            logger.error(Messages.SM_LOGERROR, ex);
        } catch (SecurityException ex) {
            Utils.showErrorBox(this, Messages.DT_SECERROR, Messages.SM_SECERROR2);
        } catch (Exception ex) {
            // ClassCastException, ClassNotFoundException, IllegalAccessException
            // IllegalArgumentException, InstantiationException, InvocationTargetException
            // NetworkAnalyzer internal error
            logger.error(Messages.SM_LOGERROR, ex);
        }

    } else {
        // Remove filter
        int res = JOptionPane.showConfirmDialog(this, Messages.SM_REMOVEFILTER, Messages.DT_REMOVEFILTER,
                JOptionPane.YES_NO_OPTION);
        if (res == JOptionPane.YES_OPTION) {
            btnFilter.setText(Messages.DI_FILTERDATA);
            btnFilter.setToolTipText(Messages.TT_FILTERDATA);
            visualizer.setComplexParam(originalParam);
            chart = visualizer.createControl();
            JFreeChartConn.setChart(chartPanel, chart);
        }
    }
}