Example usage for javax.swing JOptionPane CANCEL_OPTION

List of usage examples for javax.swing JOptionPane CANCEL_OPTION

Introduction

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

Prototype

int CANCEL_OPTION

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

Click Source Link

Document

Return value from class method if CANCEL is chosen.

Usage

From source file:edu.ku.brc.specify.tasks.subpane.wb.WorkbenchPaneSS.java

@Override
public boolean aboutToShutdown() {
    super.aboutToShutdown();

    for (WorkBenchPluginIFace wbp : workBenchPlugins.values()) {
        wbp.shutdown();//w w  w  .  j  av a 2  s . com
    }

    // Tell it is about to be hidden.
    // this way it can end any editing
    if (formPane != null) {
        if (!checkCurrentEditState()) {
            SubPaneMgr.getInstance().showPane(this);
            // Need to reverify to get the error to display again.
            if (spreadSheet.getCellEditor() != null) {
                spreadSheet.getCellEditor().stopCellEditing();
            }
            return false;
        }
    }

    if (datasetUploader != null && !datasetUploader.aboutToShutdown(this)) {
        return false;
    }

    if (datasetUploader != null) {
        if (datasetUploader.closing(this)) {
            datasetUploader = null;
            Uploader.unlockApp();
            Uploader.unlockUpload();
        }
    }

    boolean retStatus = true;
    if (hasChanged) {

        // turn off alwaysOnTop for Swing repaint reasons (prevents a lock up)
        if (imageFrame != null) {
            imageFrame.setAlwaysOnTop(false);
        }
        String msg = String.format(getResourceString("SaveChanges"), getTitle());
        JFrame topFrame = (JFrame) UIRegistry.getTopWindow();

        final String wbName = workbench.getName();

        int rv = JOptionPane.showConfirmDialog(topFrame, msg, getResourceString("SaveChangesTitle"),
                JOptionPane.YES_NO_CANCEL_OPTION);
        if (rv == JOptionPane.YES_OPTION) {
            //GlassPane and Progress bar currently don't show up during shutdown
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    UIRegistry.writeSimpleGlassPaneMsg(
                            String.format(getResourceString("WB_SAVING"), new Object[] { workbench.getName() }),
                            WorkbenchTask.GLASSPANE_FONT_SIZE);
                    UIRegistry.getStatusBar().setIndeterminate(wbName, true);
                }
            });

            SwingWorker saver = new SwingWorker() {

                /* (non-Javadoc)
                 * @see edu.ku.brc.helpers.SwingWorker#construct()
                 */
                @Override
                public Object construct() {

                    Boolean result = null;
                    try {
                        saveObject();
                        result = new Boolean(true);
                    } catch (Exception ex) {
                        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(WorkbenchPaneSS.class, ex);
                        log.error(ex);
                    }
                    return result;
                }

                /* (non-Javadoc)
                 * @see edu.ku.brc.helpers.SwingWorker#finished()
                 */
                @Override
                public void finished() {
                    UIRegistry.clearSimpleGlassPaneMsg();
                    UIRegistry.getStatusBar().setProgressDone(wbName);
                    shutdownLock.decrementAndGet();
                    shutdown();
                }

            };
            shutdownLock.incrementAndGet();
            saver.start();
            //retStatus = saver.get() != null;
        } else if (rv == JOptionPane.CANCEL_OPTION || rv == JOptionPane.CLOSED_OPTION) {
            return false;
        } else if (rv == JOptionPane.NO_OPTION) {
            hasChanged = false; // we do this so we don't get asked a second time
        }

    }

    if (retStatus) {
        ((WorkbenchTask) ContextMgr.getTaskByClass(WorkbenchTask.class)).closing(this);
        ((SGRTask) ContextMgr.getTaskByClass(SGRTask.class)).closing(this);

        if (spreadSheet != null) {
            spreadSheet.getSelectionModel().removeListSelectionListener(workbenchRowChangeListener);
        }
        workbenchRowChangeListener = null;
    }

    return retStatus;
}

From source file:com.mirth.connect.client.ui.Frame.java

public void doRemoveAllEvents() {
    int option = JOptionPane.showConfirmDialog(this,
            "All events will be removed. Would you also like them to be\n"
                    + "exported to a file on the server?");
    if (option == JOptionPane.CANCEL_OPTION || option == JOptionPane.CLOSED_OPTION) {
        return;/*from  ww w .ja va  2s.  c o  m*/
    }

    final boolean export = (option == JOptionPane.YES_OPTION);

    final String workingId = startWorking("Clearing events...");

    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

        private String exportPath = null;

        public Void doInBackground() {
            try {
                if (export) {
                    exportPath = mirthClient.exportAndRemoveAllEvents();
                } else {
                    mirthClient.removeAllEvents();
                }
            } catch (ClientException e) {
                alertThrowable(PlatformUI.MIRTH_FRAME, e);
            }
            return null;
        }

        public void done() {
            eventBrowser.runSearch();

            if (exportPath != null) {
                alertInformation(PlatformUI.MIRTH_FRAME,
                        "Events have been exported to the following server path:\n" + exportPath);
            }

            stopWorking(workingId);
        }
    };

    worker.execute();
}

From source file:it.isislab.dmason.util.SystemManagement.Master.thrower.DMasonMaster.java

private void loadUpdateFile() {
    String message = "There is no reference worker JAR. Do you want to specify a reference\n "
            + "JAR for the worker?\n" + "\n"
            + "If you choose Yes, D-Mason will ensure that every worker is running an\n"
            + "instance of the reference JAR and update them automatically.\n"
            + "If you choose No, D-Mason won't perform any check (this is highly\n"
            + "discouraged as it may lead to unreported errors during the simulation).\n"
            + "If you choose Cancel, D-Mason will exit.\n\n";

    int res = JOptionPane.showConfirmDialog(this, message);

    if (res == JOptionPane.OK_OPTION) {
        updateFile = showFileChooser();/* ww  w  .  j a  v  a  2 s  .com*/

        if (updateFile != null) {
            File dest = new File(FTP_HOME + dirSeparator + UPDATE_DIR + dirSeparator + updateFile.getName());

            try {
                FileUtils.copyFile(updateFile, dest);

                Digester dg = new Digester(DigestAlgorithm.MD5);

                InputStream in = new FileInputStream(dest);
                curWorkerDigest = dg.getDigest(in);
                workerJarName = updateFile.getName();

                String fileName = FilenameUtils.removeExtension(updateFile.getName());
                dg.storeToPropFile(FTP_HOME + dirSeparator + UPDATE_DIR + dirSeparator + fileName + ".hash");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoDigestFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        //         else
        //         {
        //            JOptionPane.showMessageDialog(this, "User aborted, D-Mason will now exit.");
        //            this.dispose();
        //            System.exit(EXIT_ON_CLOSE);
        //         }

    } else if (res == JOptionPane.NO_OPTION) {
        enableWorkersUpdate = false;
        return;
    }
    if (updateFile == null || res == JOptionPane.CANCEL_OPTION || res == JOptionPane.CLOSED_OPTION) {
        JOptionPane.showMessageDialog(this, "User aborted, D-Mason will now exit.");
        this.dispose();
        System.exit(EXIT_ON_CLOSE);
    }
}

From source file:com.mirth.connect.client.ui.Frame.java

public boolean exportChannelOnError() {
    if (isSaveEnabled()) {
        int option = JOptionPane.showConfirmDialog(this,
                "Would you like to save the channel changes locally to your computer?");
        if (option == JOptionPane.YES_OPTION) {
            if (!channelEditPanel.saveChanges()) {
                return false;
            }/*ww  w  .j av a  2  s .c  o  m*/

            boolean enabled = isSaveEnabled();
            setSaveEnabled(false);
            if (!doExportChannel()) {
                setSaveEnabled(enabled);
                return false;
            }
        } else if (option == JOptionPane.CANCEL_OPTION || option == JOptionPane.CLOSED_OPTION) {
            return false;
        } else {
            setSaveEnabled(false);
        }
    }
    return true;
}

From source file:edu.ku.brc.specify.tasks.subpane.qb.QueryBldrPane.java

@Override
public boolean aboutToShutdown() {
    boolean result = true;
    unlock();/*  w w w  .j  av  a2  s  .  c o m*/
    if (isChanged()) {
        String msg = String.format(getResourceString("SaveChanges"), getTitle());
        JFrame topFrame = (JFrame) UIRegistry.getTopWindow();

        int rv = JOptionPane.showConfirmDialog(topFrame, msg, getResourceString("SaveChangesTitle"),
                JOptionPane.YES_NO_CANCEL_OPTION);
        if (rv == JOptionPane.YES_OPTION) {
            saveQuery(false);
        } else if (rv == JOptionPane.CANCEL_OPTION || rv == JOptionPane.CLOSED_OPTION) {
            return false;
        } else if (rv == JOptionPane.NO_OPTION) {
            // nothing
        }
    }
    return result;
}

From source file:net.sourceforge.squirrel_sql.plugins.sqlscript.table_script.CreateFileOfCurrentSQLCommand.java

/**
 * Create a new unmanaged connection, , which is not associated with the current session.
 * @return a new unmanaged connection or null, if no connection can be created.
 * @throws SQLException //from w  w  w.  ja  v a  2 s .c  om
 */
private ISQLConnection createUnmanagedConnection() throws SQLException {
    ISQLConnection unmanagedConnection = getSession().createUnmanagedConnection();

    if (unmanagedConnection == null) {
        int option = JOptionPane.showConfirmDialog(null,
                "Unable to open a new connection. The current connection will be used instead.",
                "Unable to open a new Connection", JOptionPane.OK_CANCEL_OPTION);
        if (option == JOptionPane.CANCEL_OPTION) {
            return null;
        }
    } else {
        // we didn't want a autocommit
        unmanagedConnection.setAutoCommit(false);
    }
    return unmanagedConnection;
}

From source file:nl.tudelft.goal.SimpleIDE.FilePanel.java

/**
 * Helper method for {@link #handleFileRename(File, File)}. Asks the user
 * which of the given list of file references should be renamed. Returns a
 * new list of nodes that the user has selected. The given list is not
 * altered.//from w  w w.ja  v a2 s  . com
 */
private List<FileNode> filterFiles(List<FileNode> nodes) {

    ArrayList<FileNode> filteredFiles = new ArrayList<FileNode>();

    // show requester which files to change.
    // we can not dump an array of checkboxes into the showOptionDialog
    // because it will show them next to each oter instead of below each
    // other.
    // and because it does not show the OK and Cancel buttons. So we use
    // ConfirmDialog isntead
    JPanel choicespanel = new JPanel();
    choicespanel.setLayout(new BoxLayout(choicespanel, BoxLayout.Y_AXIS));
    choicespanel.add(new JLabel("There are multiple mas's using the renamed file.\n" //$NON-NLS-1$
            + "Please select which ones have to be renamed")); //$NON-NLS-1$
    ArrayList<JCheckBox> choices = new ArrayList<JCheckBox>();
    for (FileNode n : nodes) {
        JCheckBox checkbox = new JCheckBox("" //$NON-NLS-1$
                + ((FileNode) n.getParent()).getFilename());
        choices.add(checkbox);
        choicespanel.add(checkbox);
    }

    int choice = JOptionPane.showConfirmDialog(this, choicespanel, "Select files to rename", //$NON-NLS-1$
            JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
    if (choice == JOptionPane.CANCEL_OPTION) {
        return null;
    }
    // and finally copy the requested filenames to array
    for (JCheckBox c : choices) {
        if (c.isSelected()) {
            for (FileNode n : nodes) {
                if (c.getText().equals(((FileNode) n.getParent()).getFilename())) {
                    filteredFiles.add(n);
                    break;
                }
            }
        }
    }

    return filteredFiles;
}

From source file:org.bibsonomy.plugin.jabref.worker.SynchronizationWorker.java

public void run() {

    // Database Object. All operations are performed on this
    final BibtexDatabase db = this.jabRefFrame.basePanel().database();

    // Set for the entries we have fetched from Bibsonomy
    final HashSet<BibtexEntry> newEntries = new HashSet<BibtexEntry>();

    // Set of id to be removed from the database
    final HashSet<String> removeIds = new HashSet<String>();

    LogicInterface logic = getLogic();/*  w  w w  . j  a  v a2  s  .  c o  m*/
    // Iterate over all entries in the database
    for (final BibtexEntry entry : db.getEntries()) {

        final String intrahash = entry.getField("intrahash");

        // check if intrahash is present, otherwise go to next entry
        if ((intrahash == null) || (intrahash.length() == 0)) {
            // TODO: new entries shall not be added to bibsonomy? 
            continue;
        }

        try {
            // get the entry with the specific intrahash
            final Post<? extends Resource> post = logic.getPostDetails(intrahash,
                    PluginProperties.getUsername());

            if (!BibtexEntryUtil.areEqual(entry, JabRefModelConverter.convertPost(post))) {

                // show the compare dialog to let the user choose which
                // entry wants to keep
                if (!this.keepAllLocal && !this.keepAllRemote) {
                    this.status = CompareDialog.showCompareDialog(this.jabRefFrame, entry, post);
                }

                switch (this.status) {
                // upload the entry if the user chose "keep local" on the
                // compare dialog
                case CompareDialog.KEEP_LOCAL_ALWAYS:
                    this.keepAllLocal = true;
                    this.keepAllRemote = false;
                case CompareDialog.KEEP_LOCAL:

                    final List<BibtexEntry> entries = new LinkedList<BibtexEntry>();
                    entries.add(entry);

                    ExportWorker worker = new ExportWorker(this.jabRefFrame, entries);
                    WorkerUtil.performAsynchronously(worker);

                    break;

                // fetch the entry if the user choose "keep remote"
                case CompareDialog.KEEP_REMOTE_ALWAYS:
                    this.keepAllLocal = false;
                    this.keepAllRemote = true;
                case CompareDialog.KEEP_REMOTE:

                    // collect ids of entry to be removed
                    removeIds.add(entry.getId());
                    // collect the fetched entries
                    newEntries.add(JabRefModelConverter.convertPost(post));

                    break;

                case JOptionPane.CANCEL_OPTION:
                default:
                    return;
                }
            }
        } catch (final Exception e) {
            LOG.error("error during synchronization", e);
        } catch (Throwable e) {
            LOG.error("error during synchronization", e);
        }

        this.jabRefFrame.output("Synchronized " + entry.getCiteKey());

    }

    // remove the entries not needed anymore from the database
    for (final String id : removeIds) {
        db.removeEntry(id);
    }

    // add the new entries
    for (final BibtexEntry e : newEntries) {
        db.insertEntry(e);
    }

    this.keepAllRemote = false;
    this.keepAllLocal = false;

    this.jabRefFrame.output("Done.");
}

From source file:org.broad.igv.hic.MainWindow.java

private JMenuBar createMenuBar(final JPanel hiCPanel) {

    JMenuBar menuBar = new JMenuBar();

    //======== fileMenu ========
    JMenu fileMenu = new JMenu("File");

    //---- loadMenuItem ----
    JMenuItem loadMenuItem = new JMenuItem();
    loadMenuItem.setText("Load...");
    loadMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            loadMenuItemActionPerformed(e);
        }//w ww.jav  a2s  .  c  o  m
    });
    fileMenu.add(loadMenuItem);

    //---- loadFromURL ----
    JMenuItem loadFromURL = new JMenuItem();
    JMenuItem getEigenvector = new JMenuItem();
    final JCheckBoxMenuItem viewDNAseI;

    loadFromURL.setText("Load from URL ...");
    loadFromURL.setName("loadFromURL");
    loadFromURL.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            loadFromURLActionPerformed(e);
        }
    });
    fileMenu.add(loadFromURL);
    fileMenu.addSeparator();

    // Pre-defined datasets.  TODO -- generate from a file
    addPredefinedLoadItems(fileMenu);

    JMenuItem saveToImage = new JMenuItem();
    saveToImage.setText("Save to image");
    saveToImage.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            BufferedImage image = (BufferedImage) createImage(1000, 1000);
            Graphics g = image.createGraphics();
            hiCPanel.paint(g);

            JFileChooser fc = new JFileChooser();
            fc.setSelectedFile(new File("image.png"));
            int actionDialog = fc.showSaveDialog(null);
            if (actionDialog == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                if (file.exists()) {
                    actionDialog = JOptionPane.showConfirmDialog(null, "Replace existing file?");
                    if (actionDialog == JOptionPane.NO_OPTION || actionDialog == JOptionPane.CANCEL_OPTION)
                        return;
                }
                try {
                    // default if they give no format or invalid format
                    String fmt = "jpg";
                    int ind = file.getName().indexOf(".");
                    if (ind != -1) {
                        String ext = file.getName().substring(ind + 1);
                        String[] strs = ImageIO.getWriterFormatNames();
                        for (String aStr : strs)
                            if (ext.equals(aStr))
                                fmt = ext;
                    }
                    ImageIO.write(image.getSubimage(0, 0, 600, 600), fmt, file);
                } catch (IOException ie) {
                    System.err.println("Unable to write " + file + ": " + ie);
                }
            }
        }
    });
    fileMenu.add(saveToImage);
    getEigenvector = new JMenuItem("Get principal eigenvector");
    getEigenvector.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            getEigenvectorActionPerformed(e);
        }
    });
    fileMenu.add(getEigenvector);
    //---- exit ----
    JMenuItem exit = new JMenuItem();
    exit.setText("Exit");
    exit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            exitActionPerformed(e);
        }
    });
    fileMenu.add(exit);

    menuBar.add(fileMenu);

    //======== Tracks menu ========

    JMenu tracksMenu = new JMenu("Tracks");

    viewEigenvector = new JCheckBoxMenuItem("View Eigenvector...");
    viewEigenvector.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (viewEigenvector.isSelected()) {
                if (eigenvectorTrack == null) {
                    eigenvectorTrack = new EigenvectorTrack("eigen", "Eigenvectors");
                }
                updateEigenvectorTrack();
            } else {
                trackPanel.setEigenvectorTrack(null);
                if (HiCTrackManager.getLoadedTracks().isEmpty()) {
                    trackPanel.setVisible(false);
                }
            }
        }
    });
    viewEigenvector.setEnabled(false);
    tracksMenu.add(viewEigenvector);

    JMenuItem loadItem = new JMenuItem("Load...");
    loadItem.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            HiCTrackManager.loadHostedTrack(MainWindow.this);
        }

    });
    tracksMenu.add(loadItem);

    JMenuItem loadFromFileItem = new JMenuItem("Load from file...");
    loadFromFileItem.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            HiCTrackManager.loadTrackFromFile(MainWindow.this);
        }

    });
    tracksMenu.add(loadFromFileItem);

    menuBar.add(tracksMenu);

    //======== Extras menu ========
    JMenu extrasMenu = new JMenu("Extras");

    JMenuItem dumpPearsons = new JMenuItem("Dump pearsons matrix ...");
    dumpPearsons.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            BasicMatrix pearsons = hic.zd.getPearsons();
            try {
                String chr1 = hic.getChromosomes()[hic.zd.getChr1()].getName();
                String chr2 = hic.getChromosomes()[hic.zd.getChr2()].getName();
                int binSize = hic.zd.getBinSize();
                File initFile = new File("pearsons_" + chr1 + "_" + "_" + chr2 + "_" + binSize + ".bin");
                File f = FileDialogUtils.chooseFile("Save pearsons", null, initFile, FileDialogUtils.SAVE);
                if (f != null) {
                    ScratchPad.dumpPearsonsBinary(pearsons, chr1, chr2, hic.zd.getBinSize(), f);
                }
            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
        }

    });

    JMenuItem dumpEigenvector = new JMenuItem("Dump eigenvector ...");
    dumpEigenvector.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            try {
                ScratchPad.dumpEigenvector(hic);
            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
        }

    });
    extrasMenu.add(dumpEigenvector);

    JMenuItem readPearsons = new JMenuItem("Read pearsons...");
    readPearsons.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            try {
                File f = FileDialogUtils.chooseFile("Pearsons file (Yunfan format)");
                if (f != null) {
                    BasicMatrix bm = ScratchPad.readPearsons(f.getAbsolutePath());

                    hic.zd.setPearsons(bm);
                }
            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
        }

    });
    extrasMenu.add(readPearsons);

    extrasMenu.add(dumpPearsons);
    menuBar.add(extrasMenu);

    return menuBar;
}

From source file:org.broad.igv.ui.action.SetTrackHeightMenuAction.java

/**
 * Method description//from w  w  w  . j a v a2  s  . co  m
 */
final public void doSetTrackHeight() {

    boolean doRefresh = false;
    try {
        JPanel container = new JPanel();
        JLabel trackHeightLabel = new JLabel("Track Height (pixels)");
        JTextField trackHeightField = new JTextField();
        Dimension preferredSize = trackHeightField.getPreferredSize();
        trackHeightField.setPreferredSize(new Dimension(50, (int) preferredSize.getHeight()));
        container.add(trackHeightLabel);
        container.add(trackHeightField);

        int repTrackHeight = getRepresentativeTrackHeight();
        trackHeightField.setText(String.valueOf(repTrackHeight));

        int status = JOptionPane.showConfirmDialog(mainFrame.getMainFrame(), container, "Set Track Height",
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null);

        if ((status == JOptionPane.CANCEL_OPTION) || (status == JOptionPane.CLOSED_OPTION)) {
            return;
        }

        try {
            int newTrackHeight = Integer.parseInt(trackHeightField.getText().trim());
            IGV.getInstance().setAllTrackHeights(newTrackHeight);
            lastTrackHeight = newTrackHeight;
            doRefresh = true;
        } catch (NumberFormatException numberFormatException) {
            JOptionPane.showMessageDialog(mainFrame.getMainFrame(), "Track height must be an integer number.");
        }

    } finally {

        // Refresh view
        if (doRefresh) {

            // Update the state of the current tracks for drawing purposes

            mainFrame.doRefresh();
        }
        mainFrame.resetStatusMessage();
    }

}