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.mit.fss.examples.member.gui.CommSubsystemPanel.java

/**
 * Exports this panel's connectivity dataset.
 *//*from  www.  j  a  v  a  2s .com*/
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:net.sf.jabref.gui.openoffice.StyleSelectDialog.java

private void setupPopupMenu() {
    popup.add(edit);/*from   w ww  .  j a  va 2s  .co 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.ejie.uda.jsonI18nEditor.Editor.java

public boolean showConfirmDialog(String title, String message, int type) {
    return JOptionPane.showConfirmDialog(this, message, title, JOptionPane.YES_NO_OPTION, type) == 0 ? true
            : false;//from w w w .  ja v a  2s  .com
}

From source file:edu.harvard.mcz.imagecapture.jobs.JobAllImageFilesScan.java

@Override
public void start() {
    startTime = new Date();
    Singleton.getSingletonInstance().getJobList().addJob((RunnableJob) this);
    runStatus = RunStatus.STATUS_RUNNING;
    File imagebase = null; // place to start the scan from, imagebase directory for SCAN_ALL
    startPoint = null;//w ww.  j av  a 2  s. c o m
    // If it isn't null, retrieve the image base directory from properties, and test for read access.
    if (Singleton.getSingletonInstance().getProperties().getProperties()
            .getProperty(ImageCaptureProperties.KEY_IMAGEBASE) == null) {
        JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                "Can't start scan.  Don't know where images are stored.  Set imagbase property.", "Can't Scan.",
                JOptionPane.ERROR_MESSAGE);
    } else {
        imagebase = new File(Singleton.getSingletonInstance().getProperties().getProperties()
                .getProperty(ImageCaptureProperties.KEY_IMAGEBASE));
        if (imagebase != null) {
            if (imagebase.canRead()) {
                startPoint = imagebase;
            } else {
                // If it can't be read, null out imagebase
                imagebase = null;
            }
        }
        if (scan == SCAN_SPECIFIC && startPointSpecific != null && startPointSpecific.canRead()) {
            // A scan start point has been provided, don't launch a dialog.
            startPoint = startPointSpecific;
        }
        if (imagebase == null || scan == SCAN_SELECT) {
            // launch a file chooser dialog to select the directory to scan
            final JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            if (scan == SCAN_SELECT && startPointSpecific != null && startPointSpecific.canRead()) {
                fileChooser.setCurrentDirectory(startPointSpecific);
            } else {
                if (Singleton.getSingletonInstance().getProperties().getProperties()
                        .getProperty(ImageCaptureProperties.KEY_LASTPATH) != null) {
                    fileChooser.setCurrentDirectory(new File(Singleton.getSingletonInstance().getProperties()
                            .getProperties().getProperty(ImageCaptureProperties.KEY_LASTPATH)));
                }
            }
            int returnValue = fileChooser.showOpenDialog(Singleton.getSingletonInstance().getMainFrame());
            if (returnValue == JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                log.debug("Selected base directory: " + file.getName() + ".");
                startPoint = file;
            } else {
                //TODO: handle error condition
                log.error("Directory selection cancelled by user.");
            }
            //TODO: Filechooser to pick path, then save (if SCAN_ALL) imagebase property. 
            //Perhaps.  Might be undesirable behavior.
            //Probably better to warn that imagebase is null;
        }

        // TODO: Check that startPoint is or is within imagebase.
        // Check that fileToCheck is within imagebase.
        if (!ImageCaptureProperties.isInPathBelowBase(startPoint)) {
            String base = Singleton.getSingletonInstance().getProperties().getProperties()
                    .getProperty(ImageCaptureProperties.KEY_IMAGEBASE);
            log.error("Tried to scan directory (" + startPoint.getPath() + ") outside of base image directory ("
                    + base + ")");
            String message = "Can't scan and database files outside of base image directory (" + base + ")";
            JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), message,
                    "Can't Scan outside image base directory.", JOptionPane.YES_NO_OPTION);
        } else {

            // run in separate thread and allow cancellation and status reporting

            // walk through directory tree

            if (!startPoint.canRead()) {
                JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                        "Can't start scan.  Unable to read selected directory: " + startPoint.getPath(),
                        "Can't Scan.", JOptionPane.YES_NO_OPTION);
            } else {
                Singleton.getSingletonInstance().getMainFrame()
                        .setStatusMessage("Scanning " + startPoint.getPath());
                Counter counter = new Counter();
                // count files to scan
                countFiles(startPoint, counter);
                setPercentComplete(0);
                Singleton.getSingletonInstance().getMainFrame().notifyListener(runStatus, this);
                counter.incrementDirectories();
                // scan
                if (runStatus != RunStatus.STATUS_TERMINATED) {
                    checkFiles(startPoint, counter);
                }
                // report
                String report = "Scanned " + counter.getDirectories() + " directories.\n";
                report += "Created thumbnails in " + thumbnailCounter + " directories";
                if (thumbnailCounter == 0) {
                    report += " (May still be in progress)";
                }
                report += ".\n";
                if (startPointSpecific == null) {
                    report += "Starting with the base image directory (Preprocess All).\n";
                } else {
                    report += "Starting with " + startPoint.getName() + " (" + startPoint.getPath() + ")\n";
                    report += "First file: " + firstFile + " Last File: " + lastFile + "\n";
                }
                report += "Scanned  " + counter.getFilesSeen() + " files.\n";
                report += "Created  " + counter.getFilesDatabased() + " new image records.\n";
                if (counter.getFilesUpdated() > 0) {
                    report += "Updated  " + counter.getFilesUpdated() + " image records.\n";

                }
                report += "Created  " + counter.getSpecimens() + " new specimen records.\n";
                if (counter.getSpecimensUpdated() > 0) {
                    report += "Updated  " + counter.getSpecimensUpdated() + " specimen records.\n";

                }
                report += "Found " + counter.getFilesFailed() + " files with problems.\n";
                //report += counter.getErrors();
                Singleton.getSingletonInstance().getMainFrame().setStatusMessage("Preprocess scan complete");
                setPercentComplete(100);
                Singleton.getSingletonInstance().getMainFrame().notifyListener(runStatus, this);
                RunnableJobReportDialog errorReportDialog = new RunnableJobReportDialog(
                        Singleton.getSingletonInstance().getMainFrame(), report, counter.getErrors(),
                        "Preprocess Results");
                errorReportDialog.setVisible(true);
                //JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), report, "Preprocess complete", JOptionPane.ERROR_MESSAGE);
            } // can read directory
        }

        SpecimenLifeCycle sls = new SpecimenLifeCycle();
        Singleton.getSingletonInstance().getMainFrame().setCount(sls.findSpecimenCount());
    } // Imagebase isn't null
    done();
}

From source file:edu.ku.brc.specify.tools.schemalocale.SchemaLocalizerFrame.java

/**
 * /* w w  w  . j ava2s .  com*/
 */
protected void shutdown() {
    if (schemaLocPanel.hasChanged()) {
        int rv = JOptionPane.showConfirmDialog(this, getResourceString("SchemaLocalizerFrame.SV_CHNGES"), //$NON-NLS-1$
                getResourceString("SchemaLocalizerFrame.CHGS_SAVED"), JOptionPane.YES_NO_OPTION); // I18N  //$NON-NLS-1$
        if (rv == JOptionPane.YES_OPTION) {
            write();
        }
    }

    //helper.dumpAsNew(panel.getTables());
    setVisible(false);
    System.exit(0);
}

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

/**
 * Handles the pressing of the {@link #btnFilter} button.
 * <p>/*  w  w  w  . j  av  a2s .c o 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);
        }
    }
}

From source file:com.clough.android.adbv.view.UpdateTableDialog.java

private void showTableChangeOptionMenu(int x, int y, final int rowIndex) {
    JPopupMenu tableChangeOptionPopupMenu = new JPopupMenu();
    JMenuItem newRowMenuItem = new JMenuItem("Add row");
    newRowMenuItem.addActionListener(new ActionListener() {

        @Override/*from  w w w .ja  v  a 2 s .c o m*/
        public void actionPerformed(ActionEvent e) {
            new AddUpdateRowDialog(defaultTableModel, rowController, columnNames, null, -1).setVisible(true);
        }
    });
    JMenuItem updateRowMenuItem = new JMenuItem("Update row");
    updateRowMenuItem.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            Object[] row = new Object[columnNames.length];
            for (int columnIndex = 0; columnIndex < row.length; columnIndex++) {
                row[columnIndex] = defaultTableModel.getValueAt(rowIndex, columnIndex);
            }
            new AddUpdateRowDialog(defaultTableModel, rowController, columnNames, row, rowIndex)
                    .setVisible(true);
            tableColumnAdjuster.adjustColumns();
        }
    });
    JMenuItem removeRowMenuItem = new JMenuItem("Remove row");
    removeRowMenuItem.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (JOptionPane.showConfirmDialog(null, "Are you sure you want to remove this row?", "Remove row",
                    JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                defaultTableModel.removeRow(rowIndex);
                rowController.removeRow(rowIndex);
                tableColumnAdjuster.adjustColumns();
            }
        }
    });
    tableChangeOptionPopupMenu.add(newRowMenuItem);
    tableChangeOptionPopupMenu.add(updateRowMenuItem);
    tableChangeOptionPopupMenu.add(removeRowMenuItem);
    tableChangeOptionPopupMenu.show(this, x, y);
}

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  .  jav a2s. 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:eu.ggnet.dwoss.redtape.position.PositionUpdateCask.java

@Override
public boolean onOk() {
    if (StringUtils.isBlank(description)) {
        Alert.show(this, "Beschreibung darf nich leer sein.");
        return false;
    }// w w  w. java 2 s  .co m
    if (StringUtils.isBlank(positionName)) {
        Alert.show(this, "Name darf nich leer sein.");
        return false;
    }
    position.setDescription(description);
    position.setName(positionName);
    position.setAmount(amount);
    position.setTax(GlobalConfig.TAX);
    position.setBookingAccount(bookingAccount);
    try {
        position.setPrice(Double.valueOf(priceField.getText().replace(",", ".")));
        position.setAfterTaxPrice(Double.valueOf(afterTaxPriceField.getText().replace(",", ".")));
    } catch (NumberFormatException e) {
        Alert.show(this, "Preisformat ist nicht lesbar");
    }
    for (Binding binding : bindingGroup.getBindings()) {
        binding.save();
    }
    if (position.getPrice() == 0 && position.getType() != PositionType.COMMENT) {
        // TODO: We need something like Alert. e.g. Question.ask
        return JOptionPane.showConfirmDialog(this, "Preis ist 0, trotzdem fortfahren?", "Position bearbeiten",
                JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE) == 0;
    }
    for (Component component : this.getComponents()) {
        accessCos.remove(component);
    }
    return true;
}

From source file:fur.shadowdrake.minecraft.InstallPanel.java

@Deprecated
private boolean registerRhaokarLightPack(File path) throws NetworkException {
    FileOutputStream fos;/*from w  w w.jav  a2s. co  m*/

    try {
        fos = new FileOutputStream(new File(path, "modpack"));
        fos.write("rhaokar_light".getBytes());
        fos.close();
    } catch (FileNotFoundException ex) {
        return false;
    } catch (IOException ex) {
        return false;
    }
    if (new File(path, "resourcepacks/01.zip").isFile()) {
        downloadFile("manifest.json");
    } else if (new File(path, "resourcepacks/Soatex_Custom.zip").isFile()) {
        try {
            EventQueue.invokeAndWait(() -> {
                result = JOptionPane.showConfirmDialog(InstallPanel.this,
                        "An old version of the graphics pack was detected. Do you want to keep it?\nIf you choose no, your selection in addons will be downloaded.",
                        "Addons", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
            });
        } catch (InterruptedException | InvocationTargetException ex) {
            Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
        switch (result) {
        case JOptionPane.YES_OPTION:
            downloadFile("manifest_old.json", "manifest.json");
            break;
        default:
            new File(path, "mods/ShadersModCore-v2.3.31-mc1.7.10-f.jar").delete();
            try {
                cleanDirectory(new File(path, "resourcepacks"));
            } catch (IOException ex) {
            }
            try {
                deleteDirectory(new File(path, "shaderpacks"));
            } catch (IOException ex) {
            }
            downloadAddons();
        }
    }
    return true;
}