Example usage for javax.swing JOptionPane QUESTION_MESSAGE

List of usage examples for javax.swing JOptionPane QUESTION_MESSAGE

Introduction

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

Prototype

int QUESTION_MESSAGE

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

Click Source Link

Document

Used for questions.

Usage

From source file:coffeshop.PaymentPage.java

private void btnPayActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPayActionPerformed
    if (validatePayment()) {

        BigDecimal payAmt = new BigDecimal(txtPayAmt.getText());
        if (due.compareTo(payAmt) >= 0) {
            due = due.subtract(payAmt);//from w  ww.  j  a  va  2 s  . c  o  m
            paid = paid.add(payAmt);
            payments.add(new Payment(paymentMethod, transID, payAmt));
            if (cboSplit.getSelectedIndex() > 0) {
                cboSplit.setSelectedIndex(cboSplit.getSelectedIndex() - 1);
            }
            calculateDue();
            resetAll();
            JOptionPane.showConfirmDialog(null, "Do you want to print receipt?", "Payment Completed.",
                    JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(null, "Payment Amount is wrong. Please check again.",
                    "Wrong Payment Amount", JOptionPane.PLAIN_MESSAGE);
        }
        if (due.compareTo(BigDecimal.ZERO) == 0 && paid.compareTo(total) == 0) {
            JOptionPane.showMessageDialog(null, "Payment Completed.", "Payment Completed",
                    JOptionPane.PLAIN_MESSAGE);
            try {
                accessor = new DBAccessor();
                accessor.connectDB();
                if (accessor.insertPayment(emp_id, transType, transID, tax, total, promoCode, products,
                        payments)) {
                    JOptionPane.showMessageDialog(null, "Records have been saved", "Records saved",
                            JOptionPane.PLAIN_MESSAGE);
                }
                rsMan.beforeFirst();
            } catch (SQLException ex) {
                Logger.getLogger(PaymentPage.class.getName()).log(Level.SEVERE, null, ex);
            }
            main.dispose();
            main = new MainPage(rsMan);
            main.setVisible(true);
            this.dispose();
        }
    } else {
        JOptionPane.showMessageDialog(null, "Invalid payment input. Please check again.",
                "Wrong Payment Amount", JOptionPane.PLAIN_MESSAGE);
    }
}

From source file:com.nikonhacker.gui.EmulatorUI.java

/**
 * React to menu selections and toggle buttons.
 *
 * @param e the event/*from ww w  .j a  v  a  2 s .  co m*/
 */
public void actionPerformed(ActionEvent e) {
    int chip;

    if ((chip = getChipCommandMatchingAction(e, COMMAND_IMAGE_LOAD)) != Constants.CHIP_NONE) {
        openLoadImageDialog(chip);
    } else if ((chip = getChipCommandMatchingAction(e, COMMAND_ANALYSE_DISASSEMBLE)) != Constants.CHIP_NONE) {
        openAnalyseDialog(chip);
    } else if ((chip = getChipCommandMatchingAction(e, COMMAND_EMULATOR_PLAY)) != Constants.CHIP_NONE) {
        startEmulator(chip, EmulationFramework.ExecutionMode.RUN, null);
    } else if ((chip = getChipCommandMatchingAction(e, COMMAND_EMULATOR_DEBUG)) != Constants.CHIP_NONE) {
        startEmulator(chip, EmulationFramework.ExecutionMode.DEBUG, null);
    } else if ((chip = getChipCommandMatchingAction(e, COMMAND_EMULATOR_PAUSE)) != Constants.CHIP_NONE) {
        framework.pauseEmulator(chip);
    } else if ((chip = getChipCommandMatchingAction(e, COMMAND_EMULATOR_STEP)) != Constants.CHIP_NONE) {
        startEmulator(chip, EmulationFramework.ExecutionMode.STEP, null);
    } else if ((chip = getChipCommandMatchingAction(e, COMMAND_EMULATOR_STOP)) != Constants.CHIP_NONE) {
        if (framework.isEmulatorPlaying(chip)) {
            framework.pauseEmulator(chip);
        }
        if (JOptionPane.showConfirmDialog(this,
                "Are you sure you want to reset the " + Constants.CHIP_LABEL[chip]
                        + " emulator and lose the current state ?",
                "Reset ?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
            framework.stopEmulator(chip);
            reset(chip);
        }
    } else if ((chip = getChipCommandMatchingAction(e, COMMAND_SETUP_BREAKPOINTS)) != Constants.CHIP_NONE) {
        toggleBreakTriggerList(chip);
    } else if ((chip = getChipCommandMatchingAction(e,
            COMMAND_TOGGLE_MEMORY_HEX_EDITOR)) != Constants.CHIP_NONE) {
        toggleMemoryHexEditor(chip);
    } else if ((chip = getChipCommandMatchingAction(e,
            COMMAND_TOGGLE_MEMORY_ACTIVITY_VIEWER)) != Constants.CHIP_NONE) {
        toggleMemoryActivityViewer(chip);
    } else if ((chip = getChipCommandMatchingAction(e,
            COMMAND_TOGGLE_DISASSEMBLY_WINDOW)) != Constants.CHIP_NONE) {
        toggleDisassemblyLog(chip);
    } else if ((chip = getChipCommandMatchingAction(e,
            COMMAND_TOGGLE_CPUSTATE_WINDOW)) != Constants.CHIP_NONE) {
        toggleCPUState(chip);
    } else if ((chip = getChipCommandMatchingAction(e,
            COMMAND_TOGGLE_CUSTOM_LOGGER_WINDOW)) != Constants.CHIP_NONE) {
        toggleCustomMemoryRangeLoggerComponentFrame(chip);
    } else if ((chip = getChipCommandMatchingAction(e,
            COMMAND_TOGGLE_PROGRAMMABLE_TIMERS_WINDOW)) != Constants.CHIP_NONE) {
        toggleProgrammableTimersWindow(chip);
    } else if ((chip = getChipCommandMatchingAction(e,
            COMMAND_TOGGLE_CALL_STACK_WINDOW)) != Constants.CHIP_NONE) {
        toggleCallStack(chip);
    } else if ((chip = getChipCommandMatchingAction(e,
            COMMAND_TOGGLE_ITRON_OBJECT_WINDOW)) != Constants.CHIP_NONE) {
        toggleITronObject(chip);
    } else if ((chip = getChipCommandMatchingAction(e,
            COMMAND_TOGGLE_ITRON_RETURN_STACK_WINDOW)) != Constants.CHIP_NONE) {
        toggleITronReturnStack(chip);
    } else if ((chip = getChipCommandMatchingAction(e, COMMAND_SAVE_LOAD_MEMORY)) != Constants.CHIP_NONE) {
        openSaveLoadMemoryDialog(chip);
    } else if ((chip = getChipCommandMatchingAction(e,
            COMMAND_TOGGLE_CODE_STRUCTURE_WINDOW)) != Constants.CHIP_NONE) {
        toggleCodeStructureWindow(chip);
    } else if ((chip = getChipCommandMatchingAction(e,
            COMMAND_TOGGLE_SOURCE_CODE_WINDOW)) != Constants.CHIP_NONE) {
        toggleSourceCodeWindow(chip);
    } else if ((chip = getChipCommandMatchingAction(e,
            COMMAND_TOGGLE_INTERRUPT_CONTROLLER_WINDOW)) != Constants.CHIP_NONE) {
        toggleInterruptController(chip);
    } else if ((chip = getChipCommandMatchingAction(e,
            COMMAND_TOGGLE_SERIAL_INTERFACES)) != Constants.CHIP_NONE) {
        toggleSerialInterfaces(chip);
    } else if ((chip = getChipCommandMatchingAction(e, COMMAND_TOGGLE_SERIAL_DEVICES)) != Constants.CHIP_NONE) {
        toggleGenericSerialFrame(chip);
    } else if ((chip = getChipCommandMatchingAction(e,
            COMMAND_TOGGLE_IO_PORTS_WINDOW)) != Constants.CHIP_NONE) {
        toggleIoPortsWindow(chip);
    } else if ((chip = getChipCommandMatchingAction(e, COMMAND_TOGGLE_AD_CONVERTER)) != Constants.CHIP_NONE) {
        toggleAdConverterFrame(chip);
    } else if ((chip = getChipCommandMatchingAction(e, COMMAND_CHIP_OPTIONS)) != Constants.CHIP_NONE) {
        openChipOptionsDialog(chip);
    } else if (COMMAND_GENERATE_SYS_SYMBOLS.equals(e.getActionCommand())) {
        openGenerateSysSymbolsDialog();
    } else if (COMMAND_UI_OPTIONS.equals(e.getActionCommand())) {
        openUIOptionsDialog();
    } else if (COMMAND_DECODE.equals(e.getActionCommand())) {
        openDecodeDialog();
    } else if (COMMAND_ENCODE.equals(e.getActionCommand())) {
        openEncodeDialog();
    } else if (COMMAND_DECODE_NKLD.equals(e.getActionCommand())) {
        openDecodeNkldDialog();
    } else if (COMMAND_LOAD_STATE.equals(e.getActionCommand())) {
        loadState();
    } else if (COMMAND_SAVE_STATE.equals(e.getActionCommand())) {
        saveState();
    } else if (COMMAND_TOGGLE_SCREEN_EMULATOR.equals(e.getActionCommand())) {
        toggleScreenEmulator();
    } else if (COMMAND_TOGGLE_COMPONENT_4006_WINDOW.equals(e.getActionCommand())) {
        toggleComponent4006();
    }

    else if (COMMAND_TOGGLE_FRONT_PANEL.equals(e.getActionCommand())) {
        toggleFrontPanel();
    }

    else if (COMMAND_QUIT.equals(e.getActionCommand())) {
        quit();
    } else if (COMMAND_ABOUT.equals(e.getActionCommand())) {
        showAboutDialog();
    } else if (COMMAND_TEST.equals(e.getActionCommand())) {
        // noop
    } else {
        System.err.println("Unknown menu command : " + e.getActionCommand());
    }
}

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

public Channel importChannel(Channel importChannel, boolean showAlerts, boolean refreshStatuses) {
    boolean overwrite = false;

    try {//from www. j av a2 s .  co m
        String channelName = importChannel.getName();
        String tempId = parent.mirthClient.getGuid();

        // Check to see that the channel name doesn't already exist.
        if (!parent.checkChannelName(channelName, tempId)) {
            if (!parent.alertOption(parent,
                    "Would you like to overwrite the existing channel?  Choose 'No' to create a new channel.")) {
                importChannel.setRevision(0);

                do {
                    channelName = JOptionPane.showInputDialog(this, "Please enter a new name for the channel.",
                            channelName);
                    if (channelName == null) {
                        return null;
                    }
                } while (!parent.checkChannelName(channelName, tempId));

                importChannel.setName(channelName);
                setIdAndUpdateLibraries(importChannel, tempId);
            } else {
                overwrite = true;

                for (ChannelStatus channelStatus : channelStatuses.values()) {
                    Channel channel = channelStatus.getChannel();
                    if (channel.getName().equalsIgnoreCase(channelName)) {
                        // If overwriting, use the old revision number and id
                        importChannel.setRevision(channel.getRevision());
                        setIdAndUpdateLibraries(importChannel, channel.getId());
                    }
                }
            }
        } else {
            // Start the revision number over for a new channel
            importChannel.setRevision(0);

            // If the channel name didn't already exist, make sure
            // the id doesn't exist either.
            if (!checkChannelId(importChannel.getId())) {
                setIdAndUpdateLibraries(importChannel, tempId);
            }

        }

        channelStatuses.put(importChannel.getId(), new ChannelStatus(importChannel));
        parent.updateChannelTags(false);
    } catch (ClientException e) {
        parent.alertThrowable(parent, e);
    }

    // Import code templates / libraries if applicable
    parent.removeInvalidItems(importChannel.getCodeTemplateLibraries(), CodeTemplateLibrary.class);
    if (!(importChannel instanceof InvalidChannel) && !importChannel.getCodeTemplateLibraries().isEmpty()) {
        boolean importLibraries;
        String importChannelCodeTemplateLibraries = Preferences.userNodeForPackage(Mirth.class)
                .get("importChannelCodeTemplateLibraries", null);

        if (importChannelCodeTemplateLibraries == null) {
            JCheckBox alwaysChooseCheckBox = new JCheckBox(
                    "Always choose this option by default in the future (may be changed in the Administrator settings)");
            Object[] params = new Object[] {
                    "Channel \"" + importChannel.getName()
                            + "\" has code template libraries included with it. Would you like to import them?",
                    alwaysChooseCheckBox };
            int result = JOptionPane.showConfirmDialog(this, params, "Select an Option",
                    JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);

            if (result == JOptionPane.YES_OPTION || result == JOptionPane.NO_OPTION) {
                importLibraries = result == JOptionPane.YES_OPTION;
                if (alwaysChooseCheckBox.isSelected()) {
                    Preferences.userNodeForPackage(Mirth.class).putBoolean("importChannelCodeTemplateLibraries",
                            importLibraries);
                }
            } else {
                return null;
            }
        } else {
            importLibraries = Boolean.parseBoolean(importChannelCodeTemplateLibraries);
        }

        if (importLibraries) {
            CodeTemplateImportDialog dialog = new CodeTemplateImportDialog(parent,
                    importChannel.getCodeTemplateLibraries(), false, true);

            if (dialog.wasSaved()) {
                CodeTemplateLibrarySaveResult updateSummary = parent.codeTemplatePanel.attemptUpdate(
                        dialog.getUpdatedLibraries(), new HashMap<String, CodeTemplateLibrary>(),
                        dialog.getUpdatedCodeTemplates(), new HashMap<String, CodeTemplate>(), true, null,
                        null);

                if (updateSummary == null || updateSummary.isOverrideNeeded()
                        || !updateSummary.isLibrariesSuccess()) {
                    return null;
                } else {
                    for (CodeTemplateUpdateResult result : updateSummary.getCodeTemplateResults().values()) {
                        if (!result.isSuccess()) {
                            return null;
                        }
                    }
                }

                parent.codeTemplatePanel.doRefreshCodeTemplates();
            }
        }

        importChannel.getCodeTemplateLibraries().clear();
    }

    if (CollectionUtils.isNotEmpty(importChannel.getDependentIds())
            || CollectionUtils.isNotEmpty(importChannel.getDependencyIds())) {
        Set<ChannelDependency> channelDependencies = new HashSet<ChannelDependency>(
                getCachedChannelDependencies());

        if (CollectionUtils.isNotEmpty(importChannel.getDependentIds())) {
            for (String dependentId : importChannel.getDependentIds()) {
                if (StringUtils.isNotBlank(dependentId)
                        && !StringUtils.equals(dependentId, importChannel.getId())) {
                    channelDependencies.add(new ChannelDependency(dependentId, importChannel.getId()));
                }
            }
        }

        if (CollectionUtils.isNotEmpty(importChannel.getDependencyIds())) {
            for (String dependencyId : importChannel.getDependencyIds()) {
                if (StringUtils.isNotBlank(dependencyId)
                        && !StringUtils.equals(dependencyId, importChannel.getId())) {
                    channelDependencies.add(new ChannelDependency(importChannel.getId(), dependencyId));
                }
            }
        }

        if (!channelDependencies.equals(getCachedChannelDependencies())) {
            try {
                parent.mirthClient.setChannelDependencies(channelDependencies);
            } catch (ClientException e) {
                parent.alertThrowable(parent, e, "Unable to save channel dependencies.");
            }
        }

        importChannel.clearDependencies();
    }

    // Update resource names
    parent.updateResourceNames(importChannel);

    /*
     * Update the channel if we're overwriting an imported channel, if we're not showing alerts
     * (dragging/dropping multiple channels), or if we're working with an invalid channel.
     */
    if (overwrite || !showAlerts || importChannel instanceof InvalidChannel) {
        try {
            parent.updateChannel(importChannel, overwrite);

            if (importChannel instanceof InvalidChannel && showAlerts) {
                InvalidChannel invalidChannel = (InvalidChannel) importChannel;
                Throwable cause = invalidChannel.getCause();
                parent.alertThrowable(parent, cause, "Channel \"" + importChannel.getName() + "\" is invalid. "
                        + getMissingExtensions(invalidChannel) + " Original cause:\n" + cause.getMessage());
            }
        } catch (Exception e) {
            channelStatuses.remove(importChannel.getId());
            parent.updateChannelTags(false);
            parent.alertThrowable(parent, e);
            return null;
        } finally {
            if (refreshStatuses) {
                doRefreshChannels();
            }
        }
    }

    if (showAlerts) {
        final Channel importChannelFinal = importChannel;
        final boolean overwriteFinal = overwrite;

        /*
         * MIRTH-2048 - This is a hack to fix the memory access error that only occurs on OS X.
         * The block of code that edits the channel needs to be invoked later so that the screen
         * does not change before the drag/drop action of a channel finishes.
         */
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    parent.editChannel(importChannelFinal);
                    parent.setSaveEnabled(!overwriteFinal);
                } catch (Exception e) {
                    channelStatuses.remove(importChannelFinal.getId());
                    parent.updateChannelTags(false);
                    parent.alertError(parent, "Channel had an unknown problem. Channel import aborted.");
                    parent.channelEditPanel = new ChannelSetup();
                    parent.doShowChannel();
                }
            }

        });
    }

    return importChannel;
}

From source file:edu.ku.brc.specify.Specify.java

/**
 * /*from ww w. ja  v a2s .  com*/
 */
protected void checkForUpdates() {
    //UIRegistry.displayInfoMsgDlg("checkForUpdates(): checking for updates");

    String errKey = null;
    //NOTE: it looks like the "UPDATE_PATH" resource and the update url setting in i4jparams.conf need to be kept in sync
    String updatePath = UIRegistry.getResourceString("UPDATE_PATH");
    boolean doTheUpdate = false;
    try {
        // if automatic update checking is disabled, disable intentional
        // update checking also...
        // ...seems like a good idea.
        Boolean isReleaseManagedGlobally = AppContextMgr.getInstance().getClassObject(Institution.class)
                .getIsReleaseManagedGlobally();
        //         AppPreferences localPrefs = AppPreferences.getLocalPrefs();
        //         String VERSION_CHECK = "version_check.auto";
        //         boolean localChk4VersionUpdate = localPrefs.getBoolean(VERSION_CHECK, true);

        //UIRegistry.displayInfoMsgDlg("checkForUpdates(): isReleaseManagedGlobally=" + isReleaseManagedGlobally);

        doTheUpdate = (isReleaseManagedGlobally == null
                || !isReleaseManagedGlobally) /*&& localChk4VersionUpdate*/;

        //UIRegistry.displayInfoMsgDlg("checkForUpdates(): checking for updates at " + updatePath);

        UpdateDescriptor updateDesc = UpdateChecker.getUpdateDescriptor(updatePath,
                ApplicationDisplayMode.UNATTENDED);
        //UIRegistry.displayInfoMsgDlg("checkForUpdates(): UpdateDescriptor=" + updateDesc);

        if (updateDesc != null) {
            UpdateDescriptorEntry entry = updateDesc.getPossibleUpdateEntry();
            //UIRegistry.displayInfoMsgDlg("checkForUpdates(): PossibleUpdate=" + (entry != null ? entry.getNewVersion() : entry));

            if (entry != null) {
                Object[] options = { getResourceString("Specify.INSTALLUPDATE"), //$NON-NLS-1$
                        getResourceString("Specify.SKIP") //$NON-NLS-1$
                };
                if (doTheUpdate) {
                    int userChoice = JOptionPane.showOptionDialog(UIRegistry.getTopWindow(),
                            getLocalizedMessage("Specify.UPDATE_AVAIL", entry.getNewVersion()), //$NON-NLS-1$
                            getResourceString("Specify.UPDATE_AVAIL_TITLE"), //$NON-NLS-1$
                            JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,
                            options[0]);

                    if (userChoice == JOptionPane.YES_OPTION) {
                        if (!doExit(false)) {
                            return;
                        }

                    } else {
                        return;
                    }
                } else {
                    JOptionPane.showMessageDialog(UIRegistry.getTopWindow(),
                            getLocalizedMessage("Specify.UPDATE_AVAIL_BUT_UPDATES_DISABLED", //$NON-NLS-1$
                                    entry.getNewVersion()), getResourceString("Specify.UPDATE_AVAIL_TITLE"), //$NON-NLS-1$
                            JOptionPane.INFORMATION_MESSAGE);

                }
            } else {
                errKey = "Specify.NO_UPDATE_AVAIL";
            }
        } else {
            errKey = UPDATE_CHK_ERROR;
        }
    } catch (Exception ex) {
        errKey = UPDATE_CHK_ERROR;
        ex.printStackTrace();
        log.error(ex);
    }

    if (errKey != null) {
        log.error(String.format("Update Error: %s - %s", errKey, updatePath));
        UIRegistry.showLocalizedError(errKey);
        return;
    }

    if (doTheUpdate) {
        try {
            ApplicationLauncher.Callback callback = new ApplicationLauncher.Callback() {
                public void exited(int exitValue) {
                    log.error("exitValue: " + exitValue);
                    // startApp(doConfig);
                }

                public void prepareShutdown() {
                    log.error("prepareShutdown");

                }
            };
            //UIRegistry.displayInfoMsgDlg("checkForUpdates(): launching update application");
            ApplicationLauncher.launchApplication("100", getProxySettings(), true, callback);

        } catch (Exception ex) {
            log.error(ex);
            log.error("EXPCEPTION");
        }
    } else {
        //UIRegistry.showLocalizedMsg(UIRegistry.getResourceString("UPDATES_DISABLED_FOR_INSTALLATION"));
        return;
    }

}

From source file:edu.ku.brc.af.ui.forms.FormViewObj.java

public boolean isDataCompleteAndValid(final boolean throwAwayOnDiscard) {
    //log.debug((formValidator != null) +" "+ formValidator.hasChanged() +"  "+mvParent.isTopLevel() +" "+ mvParent.hasChanged());

    // Figure out if it is New and whether it has changed or is incomplete
    boolean isNewAndComplete = true;
    if (mvParent != null) {
        Object topParentData = mvParent.getTopLevel().getData();
        if (topParentData != null && topParentData instanceof FormDataObjIFace) {
            if (((FormDataObjIFace) topParentData).getId() == null) {
                if (formValidator != null && dataObj != null) {
                    isNewAndComplete = formValidator.isFormValid();
                }/*w  w w.  jav  a2s.c  o  m*/
            }
        }
    }

    //log.debug("Form     Val: "+(formValidator != null && formValidator.hasChanged()));
    //log.debug("mvParent Val: "+(mvParent != null && mvParent.isTopLevel() && mvParent.hasChanged()));

    //if ((formValidator != null && formValidator.hasChanged()) ||
    //    (mvParent != null && mvParent.isTopLevel() && mvParent.hasChanged()))
    if (!doingDiscard && mvParent != null && mvParent.isTopLevel() && mvParent.hasChanged()) {
        try {
            doingDiscard = true;
            String title = null;
            if (dataObj != null) {
                if (tableInfo == null) {
                    tableInfo = DBTableIdMgr.getInstance()
                            .getByShortClassName(dataObj.getClass().getSimpleName());
                }

                title = tableInfo != null ? tableInfo.getTitle() : null;

                if (StringUtils.isEmpty(title)) {
                    title = UIHelper.makeNamePretty(dataObj.getClass().getSimpleName());
                }
            }

            if (StringUtils.isEmpty(title)) {
                title = "data"; // I18N, not really sure what to put here.
            }

            // For the DISCARD
            // Since JOptionPane doesn't have a YES_CANCEL_OPTION 
            // I have to use YES_NO_OPTION and since this is a Discard question
            // the rv has completely different meanings:
            // YES -> Means don't save (Discard) and close dialog (return true)
            // NO  -> Means do nothing so return false

            String[] optionLabels;
            int dlgOptions;
            int defaultRV;
            if (!isNewAndComplete || (formValidator != null && !formValidator.isFormValid())) {
                dlgOptions = JOptionPane.YES_NO_OPTION;
                optionLabels = new String[] { getResourceString("DiscardChangesBtn"),
                        getResourceString("CANCEL") };
                defaultRV = JOptionPane.NO_OPTION;
            } else {
                dlgOptions = JOptionPane.YES_NO_CANCEL_OPTION;
                optionLabels = new String[] { getResourceString("SaveChangesBtn"),
                        getResourceString("DiscardChangesBtn"), getResourceString("CANCEL") };
                defaultRV = JOptionPane.CANCEL_OPTION;
            }

            int rv = JOptionPane.showOptionDialog(UIRegistry.getTopWindow(),
                    isNewAndComplete ? UIRegistry.getLocalizedMessage("DiscardChanges", title)
                            : UIRegistry.getLocalizedMessage("SaveChanges", title),
                    isNewAndComplete ? getResourceString("DiscardChangesTitle")
                            : getResourceString("SaveChangesTitle"),
                    dlgOptions, JOptionPane.QUESTION_MESSAGE, null, optionLabels, optionLabels[0]);

            if (rv == JOptionPane.CLOSED_OPTION) {
                rv = defaultRV;
            }

            if (dlgOptions == JOptionPane.YES_NO_OPTION) {
                if (rv == JOptionPane.YES_OPTION) {
                    discardCurrentObject(throwAwayOnDiscard);
                    return true;

                } else if (rv == JOptionPane.NO_OPTION) {
                    return false;
                }

            } else {
                if (rv == JOptionPane.YES_OPTION) {
                    return saveObject();

                } else if (rv == JOptionPane.CANCEL_OPTION) {
                    return false;

                } else if (rv == JOptionPane.NO_OPTION) {
                    // NO means Discard
                    discardCurrentObject(throwAwayOnDiscard);
                    return true;
                }
            }
        } finally {
            doingDiscard = false;
        }

    } else {
        return true;
    }
    return isNewAndComplete;
}

From source file:com.pironet.tda.TDA.java

/**
 * save the current logfile (only used in plugin mode)
 *///  w  ww  .j av a2s  . co m
public void saveLogFile() {
    if (fc == null) {
        fc = new JFileChooser();
        fc.setMultiSelectionEnabled(true);
        fc.setCurrentDirectory(PrefManager.get().getSelectedPath());
    }
    if (firstFile && (PrefManager.get().getPreferredSizeFileChooser().height > 0)) {
        fc.setPreferredSize(PrefManager.get().getPreferredSizeFileChooser());
    }
    int returnVal = fc.showSaveDialog(this.getRootPane());
    fc.setPreferredSize(fc.getSize());
    PrefManager.get().setPreferredSizeFileChooser(fc.getSize());

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        int selectValue = 0;
        if (file.exists()) {
            Object[] options = { "Overwrite", "Cancel" };
            selectValue = JOptionPane.showOptionDialog(null,
                    "<html><body>File exists<br><b>" + file + "</b></body></html>", "Confirm overwrite",
                    JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
        }
        if (selectValue == 0) {
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(file);
                fos.write(((LogFileContent) logFile.getUserObject()).getContent().getBytes());
                fos.flush();
            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                try {
                    fos.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}

From source file:edmondskarp.Gui.EdmondsKarpGui.java

public void saveGraph() {

    int option2 = JOptionPane.NO_OPTION;
    File f = null;// w ww .  j  av  a2s  .c om
    String str = null;
    while (option2 == JOptionPane.NO_OPTION) //Finche' non decido di salvare
    {
        //Visualizzo la finestra di dialogo
        int option = chooser.showSaveDialog(this);
        if (option == JFileChooser.APPROVE_OPTION) //Se ho premuto il tasto salva
        {
            try {
                //Recupero il file selezionato
                f = chooser.getSelectedFile();
                //Recupero il path del file
                str = f.getCanonicalPath();
                //Se il nome del file non contiene l'estensione, la aggiungo io a mano
                //Se il file esiste chiedo se lo voglio sovrascrivere
                if (f.exists()) {
                    option2 = JOptionPane.showConfirmDialog(this,
                            "Il file esiste gia'.\nLo vuoi sovrascrivere?", "Sovrascrittura",
                            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                } else {
                    option2 = JOptionPane.YES_OPTION;
                }
            } catch (IOException | HeadlessException ex) {
            }
        } else {
            option2 = JOptionPane.CANCEL_OPTION;
        }
    }
    if (option2 == JOptionPane.YES_OPTION) {
        try {
            controller.save(str);
        } catch (JSONException ex) {
            Logger.getLogger(EdmondsKarpGui.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

From source file:com.lfv.lanzius.application.Controller.java

public synchronized void closeButtonClicked() {
    if (state != CLIENT_STATE_STARTED)
        return;//from  w w  w .  j  a  v  a  2s .c  om
    if (Config.CLIENT_EXIT_DIALOG) {
        int res = JOptionPane.showConfirmDialog(view, "Are you sure you want to exit the terminal application?",
                "Exit?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (res == JOptionPane.YES_OPTION) {
            stop(true, true);
            shutdown(true);
        }
    } else {
        stop(true, true);
        shutdown(true);
    }
}

From source file:base.BasePlayer.FileRead.java

private void readVCF(File[] files) {
    try {//w ww .j a  v  a 2 s  .co  m
        if (files.length == 1 && files[0].getName().endsWith(".tbi")) {
            Main.showError("Please select vcf.gz file, not the index (.tbi)", "Error");
            return;
        }
        Main.drawCanvas.loading("Loading samples...");
        File[] addDir;
        int sampletemp = Main.samples;
        Boolean added = false;
        Sample addSample = null;
        sampleString = new StringBuffer("");

        int fileindex = -1;
        readFiles = true;
        cancelfileread = false;
        ArrayList<File> bamdirs = new ArrayList<File>();

        if (Control.controlData.controlsOn) {
            Control.dismissControls(head);
        }
        int addnumber = 0;
        for (int fi = 0; fi < files.length; fi++) {

            if (Main.cancel || !Main.drawCanvas.loading) {
                current = null;
                FileRead.head.putNext(null);
                return;
            }
            if (!files[fi].exists()) {
                continue;
            }

            addDir = null;

            if (files[fi].isDirectory()) {

                addDir = files[fi].listFiles(new FilenameFilter() {
                    public boolean accept(File dir, String name) {
                        return name.toLowerCase().endsWith(".vcf.gz") || name.toLowerCase().endsWith(".vcf");
                    }
                });
                bamdirs.add(files[fi]);
                for (int f = 0; f < addDir.length; f++) {
                    if (cancelfileread || !Main.drawCanvas.loading) {
                        current = null;
                        FileRead.head.putNext(null);
                        return;
                    }
                    if (!checkIndex(addDir[f])) {
                        Main.putMessage("Check Tools->View log");
                        ErrorLog.addError("No index file found for " + addDir[f].getName());
                    }
                    addSample = new Sample(addDir[f].getName(), (short) Main.samples,
                            addDir[f].getCanonicalPath());
                    Main.drawCanvas.sampleList.add(addSample);
                    Main.varsamples++;
                    Main.samples++;
                    Main.drawCanvas.drawVariables.visiblesamples++;
                    checkMulti(addSample);
                    addnumber++;
                    Main.drawCanvas.loadingtext = "Loading samples... " + addnumber;

                    added = true;
                    VariantHandler.commonSlider.setMaximum(Main.varsamples);
                    VariantHandler.commonSlider.setUpperValue(Main.varsamples);
                    VariantHandler.geneSlider.setMaximum(Main.varsamples);
                    sampleString.append(addSample.getName() + ";");
                    fileindex = f;
                }

            } else {
                if (!files[fi].getName().endsWith(".vcf") && !files[fi].getName().endsWith(".vcf.gz")) {
                    continue;
                }

                if (!bamdirs.contains(files[fi].getParentFile())) {
                    bamdirs.add(files[fi].getParentFile());
                }
                File testfile = null;
                boolean testing = false;
                if (!checkIndex(files[fi])) {
                    Main.putMessage("Check Tools->View log");
                    ErrorLog.addError("No index file found for " + files[fi].getName());
                    if (JOptionPane.showConfirmDialog(Main.drawScroll,
                            "No index file found. Do you want to create one?", "Indexing?",
                            JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {

                        Main.drawCanvas.loadingtext = "Creating index for " + files[fi].getName();
                        if (files[fi].getName().endsWith(".vcf.gz")) {
                            testing = true;
                            testfile = MethodLibrary.createVCFIndex(files[fi]);
                        } else {
                            MethodLibrary.createVCFIndex2(files[fi]);
                        }
                    } else {
                        continue;
                    }
                }
                if (testing && testfile != null) {
                    files[fi] = testfile;
                }
                if (fileindex > -1) {
                    if (!files[fi].getParent().equals(files[fileindex].getParent())) {
                        //   diffPaths = true;
                    }
                }
                fileindex = fi;

                addSample = new Sample(files[fi].getName(), (short) Main.samples, files[fi].getCanonicalPath());
                Main.drawCanvas.sampleList.add(addSample);
                Main.varsamples++;
                Main.samples++;
                Main.drawCanvas.drawVariables.visiblesamples = (short) Main.samples;
                sampleString.append(addSample.getName() + ";");
                checkMulti(addSample);
                addnumber++;
                Main.drawCanvas.loadingtext = "Loading samples... " + addnumber;
                added = true;
                VariantHandler.commonSlider.setMaximum(Main.varsamples);
                VariantHandler.commonSlider.setUpperValue(Main.varsamples);
                VariantHandler.geneSlider.setMaximum(Main.varsamples);

            }
        }
        if (!added) {
            Main.drawCanvas.ready("Loading samples...");
            return;
        }
        if (bamdirs.size() > 0) {

            SearchBamFiles search = new SearchBamFiles(files, bamdirs, sampletemp);
            search.execute();
        }

        Main.drawCanvas.drawVariables.visiblesamples = (short) (Main.drawCanvas.sampleList.size());
        Main.drawCanvas.checkSampleZoom();
        Main.drawCanvas.resizeCanvas(Main.drawScroll.getViewport().getWidth(),
                Main.drawScroll.getViewport().getHeight());

        int loading = 0;
        if (!(VariantHandler.hideIndels.isSelected() && VariantHandler.hideSNVs.isSelected())) {
            Main.drawCanvas.loadingtext = "Loading variants...";
            for (int i = sampletemp; i < Main.drawCanvas.sampleList.size(); i++) {
                linecounter = 0;
                if (cancelfileread || !Main.drawCanvas.loading) {
                    cancelFileRead();
                    break;
                }

                if ((Main.drawCanvas.sampleList.get(i).getIndex() + 1)
                        * Main.drawCanvas.drawVariables.sampleHeight < Main.drawScroll.getViewport().getHeight()
                                + Main.drawCanvas.drawVariables.sampleHeight) {
                    //   Main.drawCanvas.drawVariables.visibleend = (short)(Main.drawCanvas.sampleList.get(i).getIndex());      
                    //   Main.drawCanvas.drawVariables.visiblesamples = (short)(Main.drawCanvas.sampleList.get(i).getIndex()+1);   
                    Main.drawCanvas.checkSampleZoom();
                }
                Main.drawCanvas.loadbarAll = (int) ((loading
                        / (double) (Main.drawCanvas.sampleList.size() - sampletemp)) * 100);
                //   if(!Main.drawCanvas.sampleList.get(i).multipart) {       

                try {

                    //      vcfreader = new VCFFileReader(new File(Main.drawCanvas.sampleList.get(i).getTabixFile()));
                    /*  try {
                         tabixreader = new TabixReader(Main.drawCanvas.sampleList.get(i).getTabixFile());
                      }
                      catch(Exception ex) {
                         JOptionPane.showMessageDialog(Main.chromDraw, "Index file (tbi) not found for " +Main.drawCanvas.sampleList.get(i).getName(), "Error", JOptionPane.ERROR_MESSAGE);
                         ErrorLog.addError(ex.getStackTrace());
                         ex.printStackTrace();
                      }*/
                    //      iterator=null;   
                    if (Main.drawCanvas.sampleList.get(i).getTabixFile() == null) {
                        continue;
                    }

                    if (start > 10000 && end < Main.drawCanvas.splits.get(0).chromEnd - 10000) {

                        if (Main.drawCanvas.variantsEnd > 0) {
                            // iterator = tabixreader.query(Main.drawCanvas.sampleList.get(i).vcfchr +Main.chromosomeDropdown.getSelectedItem().toString()+":" +Main.drawCanvas.variantsStart +"-" +Main.drawCanvas.variantsEnd);
                            getVariants(Main.chromosomeDropdown.getSelectedItem().toString(),
                                    Main.drawCanvas.variantsStart, Main.drawCanvas.variantsEnd,
                                    Main.drawCanvas.sampleList.get(i));

                        } else {
                            Main.drawCanvas.variantsStart = start;
                            Main.drawCanvas.variantsEnd = end;
                            //  iterator = tabixreader.query(Main.drawCanvas.sampleList.get(i).vcfchr +Main.chromosomeDropdown.getSelectedItem().toString()+":" +Main.drawCanvas.variantsStart +"-" +Main.drawCanvas.variantsEnd);
                            getVariants(Main.chromosomeDropdown.getSelectedItem().toString(),
                                    Main.drawCanvas.variantsStart, Main.drawCanvas.variantsEnd,
                                    Main.drawCanvas.sampleList.get(i));

                        }
                    } else {
                        //  iterator = tabixreader.query(Main.drawCanvas.sampleList.get(i).vcfchr +Main.chromosomeDropdown.getSelectedItem().toString());
                        Main.drawCanvas.variantsStart = 0;
                        Main.drawCanvas.variantsEnd = Main.drawCanvas.splits.get(0).chromEnd;
                        getVariants(Main.chromosomeDropdown.getSelectedItem().toString(),
                                Main.drawCanvas.variantsStart, Main.drawCanvas.variantsEnd,
                                Main.drawCanvas.sampleList.get(i));

                    }
                } catch (Exception e) {
                    Main.showError(e.getMessage(), "Error");
                    ErrorLog.addError(e.getStackTrace());
                    e.printStackTrace();

                }

                /*
                 if(iterator == null) {
                    tabixreader = null;
                    continue;
                 }*/
                //    }
                /*      else {
                         continue;
                      }
                   line = null;
                          
                   current = head;      
                   first = true;
                         
                   while(true) {                     
                      try {
                         if(cancelfileread) {
                            cancelFileRead();
                                   
                           }
                         try {
                                    
                            line = iterator.next();
                         //   vcfline = vcfIterator.next();
                              
                            if(line == null) {
                               break;
                            }
                                    
                         //   line = vcfline.getSource();
                                    
                         }
                         catch(Exception ex) {
                            JOptionPane.showMessageDialog(Main.chromDraw, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                            Main.cancel();
                   //         tabixreader.mFp.close();
                            ex.printStackTrace();
                            break;
                         }
                                          
                                 
                         split = line.split("\\t+");      
                         if(Main.drawCanvas.sampleList.get(i).multiVCF) {
                                 
                            readLineMulti(split, Main.drawCanvas.sampleList.get(i));
                         }
                         else {
                                    
                            readLine(split, Main.drawCanvas.sampleList.get(i));   
                         //   readLine(vcfline, Main.drawCanvas.sampleList.get(i));
                         }
                         if(first) {
                            first = false;
                         }
                         }
                         catch(Exception e) {
                            e.printStackTrace();
                //               tabixreader.mFp.close();
                         }
                   }      
                //      tabixreader.mFp.close();
                   Main.drawCanvas.current = FileRead.head.getNext();
                           
                   if(Main.drawCanvas.splits.get(0).viewLength < 2000000) {
                              
                      Main.chromDraw.updateExons = true;
                      Main.chromDraw.repaint();
                   }
                   if(!Main.drawCanvas.loading) {
                      Draw.calculateVars = true;
                   }
                   Draw.updatevars = true;
                    Draw.updateReads = true;
                   Main.drawCanvas.repaint();
                   loading++;*/
            }

        }
        //Main.opensamples.setText("Add samples");
        checkSamples();
        annotate();

        readFiles = false;
        //   Main.drawCanvas.clusterCalc = true;
        if (Control.controlData.controlsOn) {
            Control.applyControl();
        }

        Main.bedCanvas.intersected = false;
        if (bigcalc) {
            Main.drawCanvas.calcClusters(FileRead.head);
        } else {
            Main.drawCanvas.calcClusters(FileRead.head, 1);
        }

        if (Main.bedCanvas.bedOn) {
            Main.drawCanvas.loadingtext = "Annotating variants";
            for (int i = 0; i < Main.bedCanvas.bedTrack.size(); i++) {
                if (Main.bedCanvas.bedTrack.get(i).intersect && !Main.bedCanvas.bedTrack.get(i).loading) {
                    if (Main.bedCanvas.bedTrack.get(i).small) {
                        Main.bedCanvas.annotate(Main.bedCanvas.bedTrack.get(i).getHead(),
                                FileRead.head.getNext());

                    } else {
                        BedCanvas.Annotator annotator = Main.bedCanvas.new Annotator(
                                Main.bedCanvas.bedTrack.get(i));
                        annotator.annotateVars();

                    }
                } else if (Main.bedCanvas.bedTrack.get(i).intersect && Main.bedCanvas.bedTrack.get(i).loading) {
                    Main.bedCanvas.bedTrack.get(i).waiting = true;
                }
            }
            Main.bedCanvas.intersected = true;
        }

        if (bigcalc) {
            Main.drawCanvas.calcClusters(FileRead.head);
        } else {
            Main.drawCanvas.calcClusters(FileRead.head, 1);
        }
        if (Main.drawCanvas.splits.get(0).viewLength < 2000000) {

            Main.chromDraw.updateExons = true;
            Main.chromDraw.repaint();
        }
        //   Main.drawCanvas.drawVariables.visibleend = Main.samples;
        //Main.drawCanvas.drawVariables.visiblesamples = Main.samples;
        Main.drawCanvas.checkSampleZoom();
        Main.drawCanvas.current = head;
        //   Draw.updatevars = true;
        //   Main.drawCanvas.repaint();   
        current = null;
        Main.drawCanvas.ready("Loading samples...");
        Main.drawCanvas.loadbarAll = 0;
        Main.drawCanvas.loadBarSample = 0;

    } catch (Exception e) {
        e.printStackTrace();
        ErrorLog.addError(e.getStackTrace());
    }
}

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

private void exportChannels(List<Channel> channelList) {
    if (channelHasLinkedCodeTemplates(channelList)) {
        boolean addLibraries;
        String exportChannelCodeTemplateLibraries = Preferences.userNodeForPackage(Mirth.class)
                .get("exportChannelCodeTemplateLibraries", null);

        if (exportChannelCodeTemplateLibraries == null) {
            JCheckBox alwaysChooseCheckBox = new JCheckBox(
                    "Always choose this option by default in the future (may be changed in the Administrator settings)");
            Object[] params = new Object[] {
                    "<html>One or more channels has code template libraries linked to them.<br/>Do you wish to include these libraries in each respective channel export?</html>",
                    alwaysChooseCheckBox };
            int result = JOptionPane.showConfirmDialog(this, params, "Select an Option",
                    JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);

            if (result == JOptionPane.YES_OPTION || result == JOptionPane.NO_OPTION) {
                addLibraries = result == JOptionPane.YES_OPTION;
                if (alwaysChooseCheckBox.isSelected()) {
                    Preferences.userNodeForPackage(Mirth.class).putBoolean("exportChannelCodeTemplateLibraries",
                            addLibraries);
                }/*from  www  .  j a v  a2  s  .  c o  m*/
            } else {
                return;
            }
        } else {
            addLibraries = Boolean.parseBoolean(exportChannelCodeTemplateLibraries);
        }

        if (addLibraries) {
            for (Channel channel : channelList) {
                addCodeTemplateLibrariesToChannel(channel);
            }
        }
    }

    for (Channel channel : channelList) {
        addDependenciesToChannel(channel);
    }

    JFileChooser exportFileChooser = new JFileChooser();
    exportFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

    File currentDir = new File(Frame.userPreferences.get("currentDirectory", ""));
    if (currentDir.exists()) {
        exportFileChooser.setCurrentDirectory(currentDir);
    }

    int returnVal = exportFileChooser.showSaveDialog(this);
    File exportFile = null;
    File exportDirectory = null;
    String exportPath = "/";

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        Frame.userPreferences.put("currentDirectory", exportFileChooser.getCurrentDirectory().getPath());

        int exportCollisionCount = 0;
        exportDirectory = exportFileChooser.getSelectedFile();
        exportPath = exportDirectory.getAbsolutePath();

        for (Channel channel : channelList) {
            exportFile = new File(exportPath + "/" + channel.getName() + ".xml");

            if (exportFile.exists()) {
                exportCollisionCount++;
            }

            // Update resource names
            parent.updateResourceNames(channel);
        }

        try {
            int exportCount = 0;

            boolean overwriteAll = false;
            boolean skipAll = false;
            for (int i = 0, size = channelList.size(); i < size; i++) {
                Channel channel = channelList.get(i);
                exportFile = new File(exportPath + "/" + channel.getName() + ".xml");

                boolean fileExists = exportFile.exists();
                if (fileExists) {
                    if (!overwriteAll && !skipAll) {
                        if (exportCollisionCount == 1) {
                            if (!parent.alertOption(parent, "The file " + channel.getName()
                                    + ".xml already exists.  Would you like to overwrite it?")) {
                                continue;
                            }
                        } else {
                            ConflictOption conflictStatus = parent.alertConflict(parent,
                                    "<html>The file " + channel.getName()
                                            + ".xml already exists.<br>Would you like to overwrite it?</html>",
                                    exportCollisionCount);

                            if (conflictStatus == ConflictOption.YES_APPLY_ALL) {
                                overwriteAll = true;
                            } else if (conflictStatus == ConflictOption.NO) {
                                exportCollisionCount--;
                                continue;
                            } else if (conflictStatus == ConflictOption.NO_APPLY_ALL) {
                                skipAll = true;
                                continue;
                            }
                        }
                    }
                    exportCollisionCount--;
                }

                if (!fileExists || !skipAll) {
                    String channelXML = ObjectXMLSerializer.getInstance().serialize(channel);
                    FileUtils.writeStringToFile(exportFile, channelXML, UIConstants.CHARSET);
                    exportCount++;
                }
            }

            if (exportCount > 0) {
                parent.alertInformation(parent,
                        exportCount + " files were written successfully to " + exportPath + ".");
            }
        } catch (IOException ex) {
            parent.alertError(parent, "File could not be written.");
        }
    }

    // Reset the libraries on the cached channels
    for (Channel channel : channelList) {
        channel.getCodeTemplateLibraries().clear();
        channel.clearDependencies();
    }
}