Example usage for javax.swing JOptionPane NO_OPTION

List of usage examples for javax.swing JOptionPane NO_OPTION

Introduction

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

Prototype

int NO_OPTION

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

Click Source Link

Document

Return value from class method if NO is chosen.

Usage

From source file:edu.ku.brc.specify.config.SpecifyAppContextMgr.java

/**
 * @param databaseName/*  ww w .  j  a v a 2s  .  c o m*/
 * @param userName
 * @param startingOver
 * @param doPrompt
 * @param collectionName
 * @return
 */
public CONTEXT_STATUS setContext(final String databaseName, final String userName, final boolean startingOver,
        final boolean doPrompt, final boolean isFirstTime, final String collectionName,
        final boolean isMainSpecifyApp) {
    if (debug)
        log.debug("setting context - databaseName: [" + databaseName + "] userName: [" + userName + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    this.databaseName = databaseName;
    this.userName = userName;
    this.hasContext = true;

    if (isFirstTime) {
        DBTableIdMgr.getInstance().clearPermissions();
    }

    // This is where we will read it in from the Database
    // but for now we don't need to do that.
    //
    // We need to search for User, Collection, Discipline and UserType
    // Then

    DataProviderSessionIFace session = null;
    try {
        session = openSession();

    } catch (org.hibernate.exception.SQLGrammarException ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SpecifyAppContextMgr.class, ex);
        showLocalizedError(L10N + "SCHEMA_OUTOF_SYNC"); //$NON-NLS-1$
        System.exit(0);
    }

    if (session == null) {
        return CONTEXT_STATUS.Error;
    }

    try {
        List<?> list = session.getDataList(SpecifyUser.class, "name", userName); //$NON-NLS-1$
        if (list.size() == 1) {
            user = (SpecifyUser) list.get(0);
            user.getAgents().size(); // makes sure the Agent is not lazy loaded
            session.evict(user.getAgents());
            setClassObject(SpecifyUser.class, user);

            if (!startingOver && isMainSpecifyApp) {
                if (user.getIsLoggedIn()) {
                    Object[] options = { getResourceString(L10N + "OVERRIDE"), //$NON-NLS-1$
                            getResourceString(L10N + "EXIT") //$NON-NLS-1$
                    };
                    int userChoice = JOptionPane.showOptionDialog(UIRegistry.getTopWindow(),
                            getResourceString(L10N + "LOGGED_IN"), getResourceString(L10N + "LOGGED_IN_TITLE"), //$NON-NLS-2$
                            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
                    if (userChoice == JOptionPane.NO_OPTION) {
                        //CommandDispatcher.dispatch(new CommandAction("App", "AppReqExit"));
                        System.exit(0);
                    }
                }

                user.setIsLoggedIn(true);
                user.setLoginOutTime(new Timestamp(System.currentTimeMillis()));

                try {
                    session.beginTransaction();
                    session.saveOrUpdate(user);
                    session.commit();

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

        } else {
            //JOptionPane.showMessageDialog(null, 
            //        getResourceString("USER_NOT_FOUND"), 
            //        getResourceString("USER_NOT_FOUND_TITLE"), JOptionPane.WARNING_MESSAGE);

            return CONTEXT_STATUS.Error;
            //throw new RuntimeException("The user ["+userName+"] could  not be located as a Specify user.");
        }

        // First we start by getting all the Collection that the User want to
        // work with for this "Context" then we need to go get all the Default View and
        // additional XML Resources.

        if (isFirstTime) {
            FixDBAfterLogin.fixUserPermissions(false);
        }

        if (!AppPreferences.getGlobalPrefs().getBoolean("ExsiccataUpdateFor1_7", false)) {
            FixDBAfterLogin.fixExsiccata();
        }

        Collection curColl = getClassObject(Collection.class);
        int prevCollectionId = curColl != null ? curColl.getCollectionId() : -1;

        Discipline curDis = getClassObject(Discipline.class);
        int prevDisciplineId = curDis != null ? curDis.getDisciplineId() : -1;

        classObjHash.clear();

        setClassObject(SpecifyUser.class, user);

        // Ask the User to choose which Collection they will be working with
        Collection collection = setupCurrentCollection(user, doPrompt, collectionName);
        if (collection == null) {
            // Return false but don't mess with anything that has been set up so far
            currentStatus = currentStatus == CONTEXT_STATUS.Initial ? CONTEXT_STATUS.Error
                    : CONTEXT_STATUS.Ignore;
            return currentStatus;
        }

        collection = session.merge(collection);
        String userType = user.getUserType();

        if (debug)
            log.debug("User[" + user.getName() + "] Type[" + userType + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

        userType = StringUtils.replace(userType, " ", "").toLowerCase(); //$NON-NLS-1$ //$NON-NLS-2$

        if (debug)
            log.debug("Def Type[" + userType + "]"); //$NON-NLS-1$ //$NON-NLS-2$

        spAppResourceList.clear();
        viewSetHash.clear();

        Discipline discipline = session.getData(Discipline.class, "disciplineId", //$NON-NLS-1$
                collection.getDiscipline().getId(), DataProviderSessionIFace.CompareType.Equals);
        discipline.forceLoad();

        setClassObject(Discipline.class, discipline);

        String disciplineStr = discipline.getType().toLowerCase();

        Division division = discipline.getDivision();
        division.forceLoad();
        setClassObject(Division.class, division);

        DataType dataType = discipline.getDataType();
        dataType.forceLoad();
        setClassObject(DataType.class, dataType);

        Agent userAgent = null;
        for (Agent agt : user.getAgents()) {
            if (agt.getDivision().getId().equals(division.getId())) {
                userAgent = agt;
                userAgent.getAddresses().size();
                userAgent.getVariants().size();
                break;
            }
        }
        setClassObject(Agent.class, userAgent);

        IconEntry ceEntry = IconManager.getIconEntryByName("CollectingEvent");
        if (ceEntry != null) {
            boolean isEmbedded = collection.getIsEmbeddedCollectingEvent();
            IconEntry ciEntry = IconManager
                    .getIconEntryByName(isEmbedded ? "collectinginformation" : "ce_restore");
            if (ciEntry != null) {
                ceEntry.setIcon(ciEntry.getIcon());
                ceEntry.getIcons().clear();
            }
        }

        if (isFirstTime) {
            AppPreferences.startup();

            //--------------------------------------------------------------------------------
            // Check for locks set on uploader, tree update, ...
            //--------------------------------------------------------------------------------

            int uploadLockCheckResult = Uploader.checkUploadLock(null);
            boolean noLocks = uploadLockCheckResult != Uploader.LOCKED;
            boolean goodTrees = true;
            if (uploadLockCheckResult != Uploader.LOCK_IGNORED) {
                if (noLocks) {
                    if (!discipline.getTaxonTreeDef().checkNodeRenumberingLock()) {
                        noLocks = false;
                        UIRegistry.showLocalizedError("Specify.TreeUpdateLock",
                                discipline.getTaxonTreeDef().getName());
                    }
                }
                if (noLocks) {
                    if (!discipline.getGeographyTreeDef().checkNodeRenumberingLock()) {
                        noLocks = false;
                        UIRegistry.showLocalizedError("Specify.TreeUpdateLock",
                                discipline.getGeographyTreeDef().getName());
                    }
                }
                if (noLocks) {
                    if (!division.getInstitution().getStorageTreeDef().checkNodeRenumberingLock()) {
                        noLocks = false;
                        UIRegistry.showLocalizedError("Specify.TreeUpdateLock",
                                division.getInstitution().getStorageTreeDef().getName());
                    }
                }
                if (noLocks && discipline.getGeologicTimePeriodTreeDef() != null) {
                    if (!discipline.getGeologicTimePeriodTreeDef().checkNodeRenumberingLock()) {
                        noLocks = false;
                        UIRegistry.showLocalizedError("Specify.TreeUpdateLock",
                                discipline.getGeologicTimePeriodTreeDef().getName());
                    }
                }
                if (noLocks && discipline.getLithoStratTreeDef() != null) {
                    if (!discipline.getLithoStratTreeDef().checkNodeRenumberingLock()) {
                        noLocks = false;
                        UIRegistry.showLocalizedError("Specify.TreeUpdateLock",
                                discipline.getLithoStratTreeDef().getName());
                    }
                }

                if (noLocks) {
                    // Now force node number updates for trees that are
                    // out-of-date
                    goodTrees = discipline.getTaxonTreeDef().checkNodeNumbersUpToDate(true);
                    if (goodTrees) {
                        goodTrees = discipline.getGeographyTreeDef().checkNodeNumbersUpToDate(true);
                    }
                    if (goodTrees) {
                        goodTrees = division.getInstitution().getStorageTreeDef()
                                .checkNodeNumbersUpToDate(true);
                    }
                    if (goodTrees && discipline.getGeologicTimePeriodTreeDef() != null) {
                        goodTrees = discipline.getGeologicTimePeriodTreeDef().checkNodeNumbersUpToDate(true);
                    }
                    if (goodTrees && discipline.getLithoStratTreeDef() != null) {
                        goodTrees = discipline.getLithoStratTreeDef().checkNodeNumbersUpToDate(true);
                    }
                }
            }

            if (!noLocks || !goodTrees) {
                user.setIsLoggedIn(false);
                user.setLoginOutTime(new Timestamp(System.currentTimeMillis()));
                try {
                    session.beginTransaction();
                    session.saveOrUpdate(user);
                    session.commit();

                } catch (Exception ex) {
                    edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SpecifyAppContextMgr.class,
                            ex);
                    log.error(ex);
                }
                System.exit(0);
            } else {
                user.setLoginCollectionName(collection.getCollectionName());
                user.setLoginDisciplineName(discipline.getName());
                try {
                    session.beginTransaction();
                    session.saveOrUpdate(user);
                    session.commit();

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

        DisciplineType disciplineType = DisciplineType.getDiscipline(discipline.getType());
        String folderName = disciplineType.getFolder();

        //---------------------------------------------------------
        // This is the Full Path User / Discipline / Collection / UserType / isPersonal
        // For example: rods/fish/fish/manager / true (meaning the usr's personal space)
        //---------------------------------------------------------
        String title = getResourceString(L10N + "" + PERSONALDIR);
        SpAppResourceDir appResDir = getAppResDir(session, user, discipline, collection, userType, true, title,
                true);
        //System.out.println("PERSONALDIR Dir: "+appResDir.getId()+", UT: "+appResDir.getUserType()+",  IsPers: "+appResDir.getIsPersonal()+", Disp: "+appResDir.getDisciplineType());  
        spAppResourceList.add(appResDir);
        spAppResourceHash.put(PERSONALDIR, appResDir);
        viewSetMgrHash.put(PERSONALDIR, new Pair<String, File>(null, null));

        //---------------------------------------------------------
        // This is the Full Path User / Discipline / Collection / UserType
        // For example: rods/fish/fish/manager
        //---------------------------------------------------------
        title = getResourceString(L10N + "" + USERTYPEDIR);
        appResDir = getAppResDir(session, user, discipline, collection, userType, false, title, true);
        //System.out.println("USERTYPEDIR Dir: "+appResDir.getId()+", UT: "+appResDir.getUserType()+",  IsPers: "+appResDir.getIsPersonal()+", Disp: "+appResDir.getDisciplineType());
        File dir = XMLHelper.getConfigDir(folderName + File.separator + userType);
        if (dir.exists()) {
            mergeAppResourceDirFromDiskDir(USERTYPEDIR, appResDir, disciplineStr + " " + userType, dir); //$NON-NLS-1$
        }
        spAppResourceList.add(appResDir);
        spAppResourceHash.put(USERTYPEDIR, appResDir);

        //---------------------------------------------------------
        // This is the Full Path User / Discipline / Collection
        // For example: rods/fish/fish
        //---------------------------------------------------------
        title = getResourceString(L10N + "" + COLLECTIONDIR);
        appResDir = getAppResDir(session, user, discipline, collection, null, false, title, true);
        //System.out.println("COLLECTIONDIR Dir: "+appResDir.getId()+", UT: "+appResDir.getUserType()+",  IsPers: "+appResDir.getIsPersonal()+", Disp: "+appResDir.getDisciplineType());
        spAppResourceList.add(appResDir);
        spAppResourceHash.put(COLLECTIONDIR, appResDir);
        viewSetMgrHash.put(COLLECTIONDIR, new Pair<String, File>(null, null));

        //---------------------------------------------------------
        // This is the Full Path User / Discipline
        // For example: rods/fish
        //---------------------------------------------------------
        title = getResourceString(L10N + "" + DISCPLINEDIR);
        appResDir = getAppResDir(session, user, discipline, null, null, false, title, true);
        //System.out.println("DISCPLINEDIR Dir: "+appResDir.getId()+", UT: "+appResDir.getUserType()+",  IsPers: "+appResDir.getIsPersonal()+", Disp: "+appResDir.getDisciplineType());
        dir = XMLHelper.getConfigDir(folderName);
        if (dir.exists()) {
            mergeAppResourceDirFromDiskDir(DISCPLINEDIR, appResDir, disciplineStr, dir);
        }
        spAppResourceList.add(appResDir);
        spAppResourceHash.put(DISCPLINEDIR, appResDir);

        //---------------------------------------------------------
        // Common Views 
        //---------------------------------------------------------
        title = getResourceString(L10N + "" + COMMONDIR);
        appResDir = getAppResDir(session, user, null, null, COMMONDIR, false, title, true);
        //System.out.println("COMMONDIR Dir: "+appResDir.getId()+", UT: "+appResDir.getUserType()+",  IsPers: "+appResDir.getIsPersonal()+", Disp: "+appResDir.getDisciplineType());
        dir = XMLHelper.getConfigDir("common"); //$NON-NLS-1$
        if (dir.exists()) {
            mergeAppResourceDirFromDiskDir(COMMONDIR, appResDir, COMMONDIR, dir);
            appResDir.setUserType(COMMONDIR);
        }
        spAppResourceList.add(appResDir);
        spAppResourceHash.put(COMMONDIR, appResDir);

        //---------------------------------------------------------
        // BackStop
        //---------------------------------------------------------
        String backStopStr = "backstop";
        dir = XMLHelper.getConfigDir(backStopStr); //$NON-NLS-1$
        if (dir.exists()) {
            appResDir = createAppResourceDefFromDir(BACKSTOPDIR, dir); //$NON-NLS-1$
            //System.out.println("appResDir Dir: "+appResDir.getId()+", UT: "+appResDir.getUserType()+",  IsPers: "+appResDir.getIsPersonal()+", Disp: "+appResDir.getDisciplineType());
            appResDir.setUserType(BACKSTOPDIR); //$NON-NLS-1$
            appResDir.setTitle(getResourceString(L10N + "" + BACKSTOPDIR)); //$NON-NLS-1$

            spAppResourceList.add(appResDir);
            spAppResourceHash.put(BACKSTOPDIR, appResDir);
        }

        if (isFirstTime) {
            SpecifyAppPrefs.initialPrefs();
        }

        closeSession();
        session = null;

        if (isFirstTime) {
            FixDBAfterLogin.fixDefaultDates();

            // Reset the form system because 
            // 'fixDefaultDates' loads all the forms.
            FormDevHelper.clearErrors();
            viewSetHash.clear();
            lastLoadTime = 0;

            // Now notify everyone
            if (prevDisciplineId != -1) {
                CommandDispatcher.dispatch(new CommandAction("Discipline", "Changed")); //$NON-NLS-1$ //$NON-NLS-2$
            }

            if (prevCollectionId != -1) {
                CommandDispatcher.dispatch(new CommandAction("Collection", "Changed")); //$NON-NLS-1$ //$NON-NLS-2$
            }
        }

        // We must check here before we load the schema
        checkForInitialFormats();

        session = openSession();

        // Now load the Schema, but make sure the Discipline has a localization.
        // for the current locale.
        //
        // Bug Fix 9167 - 04/01/2013 - Must always redo the Schema because any formatters at the collection level
        // otherwise will not get set
        //
        if (UIFieldFormatterMgr.isInitialized()) {
            UIFieldFormatterMgr.getInstance().shutdown();
            UIFieldFormatterMgr.getInstance().reset();
        }

        int disciplineId = getClassObject(Discipline.class).getDisciplineId();
        if (disciplineId != prevDisciplineId) {
            Locale engLocale = null;
            Locale fndLocale = null;
            Locale currLocale = SchemaI18NService.getCurrentLocale();
            List<Locale> locales = SchemaI18NService.getInstance()
                    .getLocalesFromData(SpLocaleContainer.CORE_SCHEMA, disciplineId);
            for (Locale locale : locales) {
                if (locale.equals(currLocale)) {
                    fndLocale = currLocale;
                }
                if (locale.getLanguage().equals("en")) {
                    engLocale = currLocale;
                }
            }
            if (fndLocale == null) {
                if (engLocale != null) {
                    fndLocale = engLocale;

                } else if (locales.size() > 0) {
                    fndLocale = locales.get(0);

                } else {
                    currentStatus = CONTEXT_STATUS.Error;
                    String msg = "Specify was unable to a Locale in the Schema Config for this discipline.\nPlease contact Specify support immediately.";
                    UIRegistry.showError(msg);
                    AppPreferences.shutdownAllPrefs();
                    DataProviderFactory.getInstance().shutdown();
                    DBConnection.shutdown();
                    System.exit(0);
                    return currentStatus;
                }

                fndLocale = engLocale != null ? engLocale : locales.get(0);
                SchemaI18NService.setCurrentLocale(fndLocale);
                Locale.setDefault(fndLocale);
                UIRegistry.displayErrorDlgLocalized(L10N + "NO_LOCALE", discipline.getName(),
                        currLocale.getDisplayName(), fndLocale.getDisplayName());
            }
            SchemaI18NService.getInstance().loadWithLocale(SpLocaleContainer.CORE_SCHEMA, disciplineId,
                    DBTableIdMgr.getInstance(), Locale.getDefault());
        }

        //setUpCatNumAccessionFormatters(getClassObject(Institution.class), collection);

        // We close the session here so all SpAppResourceDir get unattached to hibernate
        // because UIFieldFormatterMgr and loading views all need a session
        // and we don't want to reuse it and get a double session
        closeSession();
        session = null;

        if (isFirstTime) {
            for (DBTableInfo ti : DBTableIdMgr.getInstance().getTables()) {
                ti.setPermissions(SecurityMgr.getInstance().getPermission("DO." + ti.getName().toLowerCase()));
            }

            // Here is where you turn on View/Viewdef re-use.
            /*if (true)
            {
            boolean cacheDoVerify = ViewLoader.isDoFieldVerification();
            ViewLoader.setDoFieldVerification(false);
                    
            UIFieldFormatterMgr.getInstance();
                    
            ViewLoader.setDoFieldVerification(cacheDoVerify);
            }*/

            RegisterSpecify.register(false, 0);
        }

        return currentStatus = CONTEXT_STATUS.OK;

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

    } finally {
        if (session != null) {
            closeSession();
        }
    }

    showLocalizedError(L10N + "CRITICAL_LOGIN_ERR"); //$NON-NLS-1$
    System.exit(0);
    return null;
}

From source file:net.sf.jabref.gui.BasePanel.java

private boolean saveDatabase(File file, boolean selectedOnly, Charset enc,
        SavePreferences.DatabaseSaveType saveType) throws SaveException {
    SaveSession session;//from  ww  w . j  ava2s  .c om
    frame.block();
    final String SAVE_DATABASE = Localization.lang("Save database");
    try {
        SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs).withEncoding(enc)
                .withSaveType(saveType);
        BibtexDatabaseWriter databaseWriter = new BibtexDatabaseWriter(FileSaveSession::new);
        if (selectedOnly) {
            session = databaseWriter.savePartOfDatabase(bibDatabaseContext, mainTable.getSelectedEntries(),
                    prefs);
        } else {
            session = databaseWriter.saveDatabase(bibDatabaseContext, prefs);
        }

        registerUndoableChanges(session);

    } catch (UnsupportedCharsetException ex2) {
        JOptionPane.showMessageDialog(frame,
                Localization.lang("Could not save file.") + ' '
                        + Localization.lang("Character encoding '%0' is not supported.", enc.displayName()),
                SAVE_DATABASE, JOptionPane.ERROR_MESSAGE);
        throw new SaveException("rt");
    } catch (SaveException ex) {
        if (ex.specificEntry()) {
            // Error occurred during processing of
            // be. Highlight it:
            final int row = mainTable.findEntry(ex.getEntry());
            final int topShow = Math.max(0, row - 3);
            mainTable.setRowSelectionInterval(row, row);
            mainTable.scrollTo(topShow);
            showEntry(ex.getEntry());
        } else {
            LOGGER.warn("Could not save", ex);
        }

        JOptionPane.showMessageDialog(frame, Localization.lang("Could not save file.") + "\n" + ex.getMessage(),
                SAVE_DATABASE, JOptionPane.ERROR_MESSAGE);
        throw new SaveException("rt");

    } finally {
        frame.unblock();
    }

    boolean commit = true;
    if (!session.getWriter().couldEncodeAll()) {
        FormBuilder builder = FormBuilder.create()
                .layout(new FormLayout("left:pref, 4dlu, fill:pref", "pref, 4dlu, pref"));
        JTextArea ta = new JTextArea(session.getWriter().getProblemCharacters());
        ta.setEditable(false);
        builder.add(Localization.lang("The chosen encoding '%0' could not encode the following characters:",
                session.getEncoding().displayName())).xy(1, 1);
        builder.add(ta).xy(3, 1);
        builder.add(Localization.lang("What do you want to do?")).xy(1, 3);
        String tryDiff = Localization.lang("Try different encoding");
        int answer = JOptionPane.showOptionDialog(frame, builder.getPanel(), SAVE_DATABASE,
                JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null,
                new String[] { Localization.lang("Save"), tryDiff, Localization.lang("Cancel") }, tryDiff);

        if (answer == JOptionPane.NO_OPTION) {
            // The user wants to use another encoding.
            Object choice = JOptionPane.showInputDialog(frame, Localization.lang("Select encoding"),
                    SAVE_DATABASE, JOptionPane.QUESTION_MESSAGE, null, Encodings.ENCODINGS_DISPLAYNAMES, enc);
            if (choice == null) {
                commit = false;
            } else {
                Charset newEncoding = Charset.forName((String) choice);
                return saveDatabase(file, selectedOnly, newEncoding, saveType);

            }
        } else if (answer == JOptionPane.CANCEL_OPTION) {
            commit = false;
        }

    }

    if (commit) {
        session.commit(file.toPath());
        this.bibDatabaseContext.getMetaData().setEncoding(enc); // Make sure to remember which encoding we used.
    } else {
        session.cancel();
    }

    return commit;
}

From source file:com.itemanalysis.jmetrik.gui.Jmetrik.java

public void addTab(String title, Component p) {
    final Component P = p;
    tabbedPane.addTab(null, p);/*from   w  w  w.j a  v  a  2 s .  c o  m*/
    JmetrikTab jTab = new JmetrikTab(title);
    jTab.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int closeTabNumber = tabbedPane.indexOfComponent(P);
            JScrollPane sp = (JScrollPane) tabbedPane.getComponentAt(closeTabNumber);
            JViewport vp = sp.getViewport();

            if (vp.getComponent(0).getClass().getName().equals(JMETRIK_TEXT_FILE)) {
                int result = ((JmetrikTextFile) vp.getComponent(0)).promptToSave(Jmetrik.this);
                if (result == JOptionPane.YES_OPTION || result == JOptionPane.NO_OPTION) {
                    tabbedPane.removeTabAt(closeTabNumber);
                }
            }
        }
    });
    tabbedPane.setTabComponentAt(tabbedPane.getTabCount() - 1, jTab);
    tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);

}

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

public void importGroup(ChannelGroup importGroup, boolean showAlerts, boolean synchronous) {
    // First consolidate and import code template libraries
    Map<String, CodeTemplateLibrary> codeTemplateLibraryMap = new LinkedHashMap<String, CodeTemplateLibrary>();
    Set<String> codeTemplateIds = new HashSet<String>();

    for (Channel channel : importGroup.getChannels()) {
        if (channel.getCodeTemplateLibraries() != null) {
            for (CodeTemplateLibrary library : channel.getCodeTemplateLibraries()) {
                CodeTemplateLibrary matchingLibrary = codeTemplateLibraryMap.get(library.getId());

                if (matchingLibrary != null) {
                    for (CodeTemplate codeTemplate : library.getCodeTemplates()) {
                        if (codeTemplateIds.add(codeTemplate.getId())) {
                            matchingLibrary.getCodeTemplates().add(codeTemplate);
                        }/*from  w  w w .  j a v a  2 s.  c  o m*/
                    }
                } else {
                    matchingLibrary = library;
                    codeTemplateLibraryMap.put(matchingLibrary.getId(), matchingLibrary);

                    List<CodeTemplate> codeTemplates = new ArrayList<CodeTemplate>();
                    for (CodeTemplate codeTemplate : matchingLibrary.getCodeTemplates()) {
                        if (codeTemplateIds.add(codeTemplate.getId())) {
                            codeTemplates.add(codeTemplate);
                        }
                    }
                    matchingLibrary.setCodeTemplates(codeTemplates);
                }

                // Combine the library enabled / disabled channel IDs
                matchingLibrary.getEnabledChannelIds().addAll(library.getEnabledChannelIds());
                matchingLibrary.getEnabledChannelIds().add(channel.getId());
                matchingLibrary.getDisabledChannelIds().addAll(library.getDisabledChannelIds());
                matchingLibrary.getDisabledChannelIds().removeAll(matchingLibrary.getEnabledChannelIds());
            }

            channel.getCodeTemplateLibraries().clear();
        }
    }

    List<CodeTemplateLibrary> codeTemplateLibraries = new ArrayList<CodeTemplateLibrary>(
            codeTemplateLibraryMap.values());

    parent.removeInvalidItems(codeTemplateLibraries, CodeTemplateLibrary.class);
    if (CollectionUtils.isNotEmpty(codeTemplateLibraries)) {
        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[] {
                    "Group \"" + importGroup.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;
            }
        } else {
            importLibraries = Boolean.parseBoolean(importChannelCodeTemplateLibraries);
        }

        if (importLibraries) {
            CodeTemplateImportDialog dialog = new CodeTemplateImportDialog(parent, codeTemplateLibraries, 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;
                } else {
                    for (CodeTemplateUpdateResult result : updateSummary.getCodeTemplateResults().values()) {
                        if (!result.isSuccess()) {
                            return;
                        }
                    }
                }

                parent.codeTemplatePanel.doRefreshCodeTemplates();
            }
        }
    }

    List<Channel> successfulChannels = new ArrayList<Channel>();
    for (Channel channel : importGroup.getChannels()) {
        Channel importChannel = importChannel(channel, false, false);
        if (importChannel != null) {
            successfulChannels.add(importChannel);
        }
    }

    if (!StringUtils.equals(importGroup.getId(), ChannelGroup.DEFAULT_ID)) {
        ChannelTreeTableModel model = (ChannelTreeTableModel) channelTable.getTreeTableModel();
        AbstractChannelTableNode importGroupNode = null;

        String groupName = importGroup.getName();
        String tempId;
        try {
            tempId = parent.mirthClient.getGuid();
        } catch (ClientException e) {
            tempId = UUID.randomUUID().toString();
        }

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

                do {
                    groupName = JOptionPane.showInputDialog(this, "Please enter a new name for the group.",
                            groupName);
                    if (groupName == null) {
                        return;
                    }
                } while (!checkGroupName(groupName));

                importGroup.setId(tempId);
                importGroup.setName(groupName);
            } else {
                MutableTreeTableNode root = (MutableTreeTableNode) model.getRoot();
                for (Enumeration<? extends MutableTreeTableNode> groupNodes = root.children(); groupNodes
                        .hasMoreElements();) {
                    AbstractChannelTableNode groupNode = (AbstractChannelTableNode) groupNodes.nextElement();

                    if (StringUtils.equals(groupNode.getGroupStatus().getGroup().getName(), groupName)) {
                        importGroupNode = groupNode;
                    }
                }
            }
        } else {
            // Start the revision number over for a new channel group
            importGroup.setRevision(0);

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

        Set<ChannelGroup> channelGroups = new HashSet<ChannelGroup>();
        Set<String> removedChannelGroupIds = new HashSet<String>(groupStatuses.keySet());
        removedChannelGroupIds.remove(ChannelGroup.DEFAULT_ID);

        MutableTreeTableNode root = (MutableTreeTableNode) channelTable.getTreeTableModel().getRoot();
        if (root == null) {
            return;
        }

        for (Enumeration<? extends MutableTreeTableNode> groupNodes = root.children(); groupNodes
                .hasMoreElements();) {
            ChannelGroup group = ((AbstractChannelTableNode) groupNodes.nextElement()).getGroupStatus()
                    .getGroup();

            if (!StringUtils.equals(group.getId(), ChannelGroup.DEFAULT_ID)) {
                // If the current group is the one we're overwriting, merge the channels
                if (importGroupNode != null && StringUtils.equals(group.getId(),
                        importGroupNode.getGroupStatus().getGroup().getId())) {
                    group = importGroup;
                    group.setRevision(importGroupNode.getGroupStatus().getGroup().getRevision());

                    Set<String> channelIds = new HashSet<String>();
                    for (Channel channel : group.getChannels()) {
                        channelIds.add(channel.getId());
                    }

                    // Add the imported channels
                    for (Channel channel : successfulChannels) {
                        channelIds.add(channel.getId());
                    }

                    List<Channel> channels = new ArrayList<Channel>();
                    for (String channelId : channelIds) {
                        channels.add(new Channel(channelId));
                    }
                    group.setChannels(channels);
                }

                channelGroups.add(group);
                removedChannelGroupIds.remove(group.getId());
            }
        }

        if (importGroupNode == null) {
            List<Channel> channels = new ArrayList<Channel>();
            for (Channel channel : successfulChannels) {
                channels.add(new Channel(channel.getId()));
            }
            importGroup.setChannels(channels);

            channelGroups.add(importGroup);
            removedChannelGroupIds.remove(importGroup.getId());
        }

        Set<String> channelIds = new HashSet<String>();
        for (Channel channel : importGroup.getChannels()) {
            channelIds.add(channel.getId());
        }

        for (ChannelGroup group : channelGroups) {
            if (group != importGroup) {
                for (Iterator<Channel> channels = group.getChannels().iterator(); channels.hasNext();) {
                    if (!channelIds.add(channels.next().getId())) {
                        channels.remove();
                    }
                }
            }
        }

        attemptUpdate(channelGroups, removedChannelGroupIds, false);
    }

    if (synchronous) {
        retrieveChannels();
        updateModel(getCurrentTableState());
        updateTasks();
        parent.setSaveEnabled(false);
    } else {
        doRefreshChannels();
    }
}

From source file:com.pianobakery.complsa.MainGui.java

public void impSearchCorpMethod() {

    logger.debug("Numeric?: " + StringUtils.isNumeric(amountSearchCorpSent.getText()));
    logger.debug("Chunk selected: " + splitSearchCorpCheckBox.isSelected());

    if (splitSearchCorpCheckBox.isSelected() && !StringUtils.isNumeric(amountSearchCorpSent.getText())) {

        JOptionPane.showMessageDialog(null, "Enter Number");
        return;/*from  ww  w  .  ja  va  2  s . c o m*/

    }

    File folder = chooseAddCorpusFolder();

    if (folder != null) {

        File newDir = new File(wDir + File.separator + searchFolder + File.separator + folder.getName());
        logger.debug("Corpus Folder: " + folder.toString());
        logger.debug("Import Folder: " + newDir.toString());
        logger.debug("Working Folder : " + wDir.toString());
        logger.debug("Corpus Folder recursive is: " + impSearchCorpRecursiveCheckBox.isSelected());

        //Create Corpus Folder
        if (!newDir.exists()) {

            logger.debug("Creating directory: " + newDir);
            boolean result = false;

            try {
                FileUtils.forceMkdir(newDir);
                addRemoveItemToTopicSearchBoxTaskWithBar(getProgressBarWithTitleLater("Please wait...", false),
                        newDir, true, false);
                //addRemoveItemToTopicBox(newDir, true, false);
                result = true;
            } catch (SecurityException se) {
                JOptionPane.showMessageDialog(null, "No permission or File Exists");

                //return Boolean.FALSE;
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            if (result) {
                logger.debug("DIR created");
            }
        } else {

            int result = JOptionPane.showConfirmDialog(new JFrame(),
                    "Folder exists, add to your Search Corpus?");
            logger.debug("DIR not created");
            if (result == JOptionPane.NO_OPTION | result == JOptionPane.CANCEL_OPTION) {
                return;
            }

        }

        //Run import
        if (folder != null) {
            addTopicCorpTaskWithBar(getProgressBarWithTitleLater("Add Topic Corpus", true), folder, newDir,
                    addCorpRecursiveCheckBox.isSelected(), Integer.parseInt(amountSearchCorpSent.getText()),
                    splitSearchCorpCheckBox.isSelected());

        }

    }

}

From source file:com.pianobakery.complsa.MainGui.java

public void removeSearchCorpMethod() {
    File theFile = searchCorpusModel.get(searchCorpComboBox.getSelectedItem());

    int result = JOptionPane.showConfirmDialog(null, "Do you want to continue?", "Confirm",
            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
    if (result == JOptionPane.NO_OPTION || result == JOptionPane.CANCEL_OPTION) {
        return;/*from w ww .  ja va2  s. c om*/
    }

    if (theFile != null) {
        addRemoveItemToTopicSearchBoxTaskWithBar(getProgressBarWithTitleLater("Please wait...", false), theFile,
                false, false);
        //addRemoveItemToTopicBox(theFile, false, false);
    } else if (theFile == null) {

        try {
            searchCorpComboBox.removeItemAt(0);
            System.out.printf("Items of select Search Corps: " + searchCorpComboBox.getItemAt(0));

        } catch (ArrayIndexOutOfBoundsException e2) {
            JOptionPane.showMessageDialog(null, "Keine Search Corps mehr vorhanden");
        }

    }

}

From source file:marytts.tools.redstart.AdminWindow.java

private void jMenuItem_ImportTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_ImportTextActionPerformed
    JFileChooser fc = new JFileChooser(new File(voiceFolderPathString));
    fc.setDialogTitle("Choose text file to import");
    //fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int returnVal = fc.showOpenDialog(this);
    if (returnVal != JFileChooser.APPROVE_OPTION)
        return;//from   w  w  w  .j a v  a 2 s  . co  m
    File file = fc.getSelectedFile();
    if (file == null)
        return;
    String[] lines = null;
    try {
        lines = StringUtils.readTextFile(file.getAbsolutePath(), "UTF-8");
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    if (lines == null || lines.length == 0)
        return;
    Object[] options = new Object[] { "Keep first column", "Discard first column" };
    int answer = JOptionPane.showOptionDialog(this,
            "File contains " + lines.length + " sentences.\n" + "Sample line:\n" + lines[0] + "\n"
                    + "Keep or discard first column?",
            "Import details", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,
            options[1]);
    boolean discardFirstColumn = (answer == JOptionPane.NO_OPTION);

    String prefix = (String) JOptionPane.showInputDialog(this,
            "Prefix to use for individual sentence filenames:", "Choose filename prefix",
            JOptionPane.PLAIN_MESSAGE, null, null, "s");
    int numDigits = (int) Math.log10(lines.length) + 1;
    String pattern = prefix + "%0" + numDigits + "d.txt";
    File scriptFile = new File(voiceFolderPathString + "/" + file.getName() + ".script.txt");
    PrintWriter scriptWriter = null;
    try {
        scriptWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(scriptFile), "UTF-8"));
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this,
                "Cannot write to script file " + scriptFile.getAbsolutePath() + ":\n" + e.getMessage());
        if (scriptWriter != null)
            scriptWriter.close();
        return;
    }
    File textFolder = getPromptFolderPath();

    // if filename ends with ".txt_tr" then it has also transcriptions in it
    String selectedFile_ext = FilenameUtils.getExtension(file.getName());
    Boolean inputHasAlsoTranscription = false;
    File transcriptionFolder = new File("");

    // transcription folder name, and makedir
    if (selectedFile_ext.equals("txt_tr")) {
        System.out.println("txt_tr");
        if (lines.length % 2 == 0) {
            // even
        } else {
            // odd
            System.err.println(".txt_tr file has an odd number of lines, so it's corrupted, exiting.");
            System.exit(0);
        }
        inputHasAlsoTranscription = true;
        String transcriptionFolderName = voiceFolderPathString + AdminWindow.TRANSCRIPTION_FOLDER_NAME;
        transcriptionFolder = new File(transcriptionFolderName);
        if (transcriptionFolder.exists()) {
            System.out.println("transcription folder already exists");
        } else {
            if (transcriptionFolder.mkdirs()) {
                System.out.println("transcription folder created");
            } else {
                System.err.println("Cannot create transcription folder -- exiting.");
                System.exit(0);
            }
        }
    } else {
        System.out.println("input file extension is not txt_tr, but " + selectedFile_ext
                + ", so it contains ortographic sentences without transcriptions.");
    }

    for (int i = 0; i < lines.length; i++) {
        String line = lines[i];
        if (discardFirstColumn)
            line = line.substring(line.indexOf(' ') + 1);
        int sent_index = i + 1;
        if (inputHasAlsoTranscription == true) {
            sent_index = i / 2 + 1;
        }

        String filename = String.format(pattern, sent_index);
        System.out.println(filename + " " + line);
        File textFile = new File(textFolder, filename);
        if (textFile.exists()) {
            JOptionPane.showMessageDialog(this, "Cannot writing file " + filename + ":\n" + "File exists!\n"
                    + "Aborting text file import.");
            return;
        }
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(textFile), "UTF-8"));
            pw.println(line);
            scriptWriter.println(filename.substring(0, filename.lastIndexOf('.')) + " " + line);
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(this, "Error writing file " + filename + ":\n" + ioe.getMessage());
            ioe.printStackTrace();
            return;
        } finally {
            if (pw != null)
                pw.close();
        }

        // transcription case:
        if (inputHasAlsoTranscription == true) {
            // modify pattern: best would be something like sed "s/.txt$/.tr$/"
            // easy but dirty:
            String transc_pattern = pattern.replace(".txt", ".tr");
            filename = String.format(transc_pattern, sent_index);
            i++;
            line = lines[i];
            if (discardFirstColumn)
                line = line.substring(line.indexOf(' ') + 1);
            File transcriptionTextFile = new File(transcriptionFolder, filename);
            if (transcriptionTextFile.exists()) {
                JOptionPane.showMessageDialog(this, "Cannot writing file " + transcriptionTextFile.getName()
                        + ":\n" + "File exists!\n" + "Aborting text file import.");
                return;
            }
            pw = null;
            try {
                pw = new PrintWriter(
                        new OutputStreamWriter(new FileOutputStream(transcriptionTextFile), "UTF-8"));
                pw.println(line);
                scriptWriter.println(filename.substring(0, filename.lastIndexOf('.')) + " " + line);
            } catch (IOException ioe) {
                JOptionPane.showMessageDialog(this,
                        "Error writing file " + filename + ":\n" + ioe.getMessage());
                ioe.printStackTrace();
                return;
            } finally {
                if (pw != null)
                    pw.close();
            }
        }

    }
    scriptWriter.close();
    setupVoice();
}

From source file:GUI.MainWindow.java

private void jMenuItem8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem8ActionPerformed
    System.out.println("Export to excel clicked");
    DefaultTreeModel dtm = (DefaultTreeModel) this.VulnTree.getModel();
    DefaultMutableTreeNode root = (DefaultMutableTreeNode) dtm.getRoot();
    System.out.println("Child Count: " + root.getChildCount());
    if (root.getChildCount() == 0) {
        System.out.println("No vulns in tree. Halting the export");
        return;//from w  w w  . j a  v  a 2  s .com
    }

    // If we get here then there are some vulns.
    // Prompt for an export file.
    boolean proceed = true;
    int returnVal = this.fileChooser.showSaveDialog(this);

    if (returnVal == JFileChooser.APPROVE_OPTION) {

        File save_file = fileChooser.getSelectedFile();
        System.out.println(save_file);

        if (save_file.exists() == true) {

            int response = JOptionPane.showConfirmDialog(null,
                    "Are you sure you want to replace existing file?", "Confirm", JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE);
            if (response == JOptionPane.NO_OPTION) {
                proceed = false;
            }
        }

        if (proceed == true) {

            ExportToExcel excelOut = new ExportToExcel();
            try {
                excelOut.writeExcel(save_file, root);
            } catch (IOException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(null, ex);
            } catch (WriteException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(null, ex);
            }

        }

    }

}

From source file:userinterface.properties.GUIGraphHandler.java

public void defineConstantsAndPlot(Expression expr, JPanel graph, String seriesName, Boolean isNewGraph,
        boolean is2D) {

    JDialog dialog;//from w w w .j  a va 2s.  c o  m
    JButton ok, cancel;
    JScrollPane scrollPane;
    ConstantPickerList constantList;
    JComboBox<String> xAxis, yAxis;

    //init everything
    dialog = new JDialog(GUIPrism.getGUI());
    dialog.setTitle("Define constants and select axes");
    dialog.setSize(500, 400);
    dialog.setLocationRelativeTo(GUIPrism.getGUI());
    dialog.setLayout(new BoxLayout(dialog.getContentPane(), BoxLayout.Y_AXIS));
    dialog.setModal(true);

    constantList = new ConstantPickerList();
    scrollPane = new JScrollPane(constantList);

    xAxis = new JComboBox<String>();
    yAxis = new JComboBox<String>();

    ok = new JButton("Ok");
    ok.setMnemonic('O');
    cancel = new JButton("Cancel");
    cancel.setMnemonic('C');

    //add all components to their dedicated panels
    JPanel exprPanel = new JPanel(new FlowLayout());
    exprPanel.setBorder(new TitledBorder("Function"));
    exprPanel.add(new JLabel(expr.toString()));

    JPanel axisPanel = new JPanel();
    axisPanel.setBorder(new TitledBorder("Select axis constants"));
    axisPanel.setLayout(new BoxLayout(axisPanel, BoxLayout.Y_AXIS));
    JPanel xAxisPanel = new JPanel(new FlowLayout());
    xAxisPanel.add(new JLabel("X axis:"));
    xAxisPanel.add(xAxis);
    JPanel yAxisPanel = new JPanel(new FlowLayout());
    yAxisPanel.add(new JLabel("Y axis:"));
    yAxisPanel.add(yAxis);
    axisPanel.add(xAxisPanel);
    axisPanel.add(yAxisPanel);

    JPanel constantPanel = new JPanel(new BorderLayout());
    constantPanel.setBorder(new TitledBorder("Please define the following constants"));
    constantPanel.add(scrollPane, BorderLayout.CENTER);
    constantPanel.add(new ConstantHeader(), BorderLayout.NORTH);

    JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    bottomPanel.add(ok);
    bottomPanel.add(cancel);

    //fill the axes components

    for (int i = 0; i < expr.getAllConstants().size(); i++) {

        xAxis.addItem(expr.getAllConstants().get(i));

        if (!is2D)
            yAxis.addItem(expr.getAllConstants().get(i));
    }

    if (!is2D) {
        yAxis.setSelectedIndex(1);
    }

    //fill the constants table

    for (int i = 0; i < expr.getAllConstants().size(); i++) {

        ConstantLine line = new ConstantLine(expr.getAllConstants().get(i), TypeDouble.getInstance());
        constantList.addConstant(line);

        if (!is2D) {
            if (line.getName().equals(xAxis.getSelectedItem().toString())
                    || line.getName().equals(yAxis.getSelectedItem().toString())) {

                line.doFuncEnables(false);
            } else {
                line.doFuncEnables(true);
            }
        }

    }

    //do enables

    if (is2D) {
        yAxis.setEnabled(false);
    }

    ok.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "ok");
    ok.getActionMap().put("ok", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            ok.doClick();
        }
    });

    cancel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
            "cancel");
    cancel.getActionMap().put("cancel", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            cancel.doClick();
        }
    });

    //add action listeners

    xAxis.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (is2D) {
                return;
            }

            String item = xAxis.getSelectedItem().toString();

            if (item.equals(yAxis.getSelectedItem().toString())) {

                int index = yAxis.getSelectedIndex();

                if (index != yAxis.getItemCount() - 1) {
                    yAxis.setSelectedIndex(++index);
                } else {
                    yAxis.setSelectedIndex(--index);
                }

            }

            for (int i = 0; i < constantList.getNumConstants(); i++) {

                ConstantLine line = constantList.getConstantLine(i);

                if (line.getName().equals(xAxis.getSelectedItem().toString())
                        || line.getName().equals(yAxis.getSelectedItem().toString())) {

                    line.doFuncEnables(false);
                } else {

                    line.doFuncEnables(true);
                }

            }
        }
    });

    yAxis.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            String item = yAxis.getSelectedItem().toString();

            if (item.equals(xAxis.getSelectedItem().toString())) {

                int index = xAxis.getSelectedIndex();

                if (index != xAxis.getItemCount() - 1) {
                    xAxis.setSelectedIndex(++index);
                } else {
                    xAxis.setSelectedIndex(--index);
                }
            }

            for (int i = 0; i < constantList.getNumConstants(); i++) {

                ConstantLine line = constantList.getConstantLine(i);

                if (line.getName().equals(xAxis.getSelectedItem().toString())
                        || line.getName().equals(yAxis.getSelectedItem().toString())) {

                    line.doFuncEnables(false);
                } else {

                    line.doFuncEnables(true);
                }

            }
        }
    });

    ok.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            try {

                constantList.checkValid();

            } catch (PrismException e2) {
                JOptionPane.showMessageDialog(dialog,
                        "<html> One or more of the defined constants are invalid. <br><br> <font color=red>Error: </font>"
                                + e2.getMessage() + "</html>",
                        "Parse Error", JOptionPane.ERROR_MESSAGE);
                return;
            }

            if (is2D) {

                // it will always be a parametric graph in 2d case
                ParametricGraph pGraph = (ParametricGraph) graph;

                ConstantLine xAxisConstant = constantList.getConstantLine(xAxis.getSelectedItem().toString());

                if (xAxisConstant == null) {
                    //should never happen
                    JOptionPane.showMessageDialog(dialog, "The selected axis is invalid.", "Error",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                }

                double xStartValue = Double.parseDouble(xAxisConstant.getStartValue());
                double xEndValue = Double.parseDouble(xAxisConstant.getEndValue());
                double xStepValue = Double.parseDouble(xAxisConstant.getStepValue());

                int seriesCount = 0;

                for (int i = 0; i < constantList.getNumConstants(); i++) {

                    ConstantLine line = constantList.getConstantLine(i);

                    if (line.getName().equals(xAxis.getSelectedItem().toString())) {
                        seriesCount++;
                    } else {

                        seriesCount += line.getTotalNumOfValues();

                    }
                }

                // if there will be too many series to be plotted, ask the user if they are sure they know what they are doing
                if (seriesCount > 10) {

                    int res = JOptionPane.showConfirmDialog(dialog,
                            "This configuration will create " + seriesCount + " series. Continue?", "Confirm",
                            JOptionPane.YES_NO_OPTION);

                    if (res == JOptionPane.NO_OPTION) {
                        return;
                    }

                }

                Values singleValuesGlobal = new Values();

                //add the single values to a global values list

                for (int i = 0; i < constantList.getNumConstants(); i++) {

                    ConstantLine line = constantList.getConstantLine(i);

                    if (line.getTotalNumOfValues() == 1) {

                        double singleValue = Double.parseDouble(line.getSingleValue());
                        singleValuesGlobal.addValue(line.getName(), singleValue);
                    }
                }

                // we just have one variable so we can plot directly
                if (constantList.getNumConstants() == 1
                        || singleValuesGlobal.getNumValues() == constantList.getNumConstants() - 1) {

                    SeriesKey key = pGraph.addSeries(seriesName);

                    pGraph.hideShape(key);
                    pGraph.getXAxisSettings().setHeading(xAxis.getSelectedItem().toString());
                    pGraph.getYAxisSettings().setHeading("function");

                    for (double x = xStartValue; x <= xEndValue; x += xStepValue) {

                        double ans = -1;

                        Values vals = new Values();
                        vals.addValue(xAxis.getSelectedItem().toString(), x);

                        for (int ii = 0; ii < singleValuesGlobal.getNumValues(); ii++) {

                            try {
                                vals.addValue(singleValuesGlobal.getName(ii),
                                        singleValuesGlobal.getDoubleValue(ii));
                            } catch (PrismLangException e1) {
                                e1.printStackTrace();
                            }

                        }

                        try {
                            ans = expr.evaluateDouble(vals);
                        } catch (PrismLangException e1) {
                            e1.printStackTrace();
                        }

                        pGraph.addPointToSeries(key, new PrismXYDataItem(x, ans));

                    }

                    if (isNewGraph) {
                        addGraph(pGraph);
                    }

                    dialog.dispose();
                    return;
                }

                for (int i = 0; i < constantList.getNumConstants(); i++) {

                    ConstantLine line = constantList.getConstantLine(i);

                    if (line == xAxisConstant || singleValuesGlobal.contains(line.getName())) {
                        continue;
                    }

                    double lineStart = Double.parseDouble(line.getStartValue());
                    double lineEnd = Double.parseDouble(line.getEndValue());
                    double lineStep = Double.parseDouble(line.getStepValue());

                    for (double j = lineStart; j < lineEnd; j += lineStep) {

                        SeriesKey key = pGraph.addSeries(seriesName);
                        pGraph.hideShape(key);

                        for (double x = xStartValue; x <= xEndValue; x += xStepValue) {

                            double ans = -1;

                            Values vals = new Values();
                            vals.addValue(xAxis.getSelectedItem().toString(), x);
                            vals.addValue(line.getName(), j);

                            for (int ii = 0; ii < singleValuesGlobal.getNumValues(); ii++) {

                                try {
                                    vals.addValue(singleValuesGlobal.getName(ii),
                                            singleValuesGlobal.getDoubleValue(ii));
                                } catch (PrismLangException e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                }

                            }

                            for (int ii = 0; ii < constantList.getNumConstants(); ii++) {

                                if (constantList.getConstantLine(ii) == xAxisConstant
                                        || singleValuesGlobal
                                                .contains(constantList.getConstantLine(ii).getName())
                                        || constantList.getConstantLine(ii) == line) {

                                    continue;
                                }

                                ConstantLine temp = constantList.getConstantLine(ii);
                                double val = Double.parseDouble(temp.getStartValue());

                                vals.addValue(temp.getName(), val);
                            }

                            try {
                                ans = expr.evaluateDouble(vals);
                            } catch (PrismLangException e1) {
                                e1.printStackTrace();
                            }

                            pGraph.addPointToSeries(key, new PrismXYDataItem(x, ans));
                        }
                    }

                }

                if (isNewGraph) {
                    addGraph(graph);
                }
            } else {

                // this will always be a parametric graph for the 3d case
                ParametricGraph3D pGraph = (ParametricGraph3D) graph;

                //add the graph to the gui
                addGraph(pGraph);

                //Get the constants we want to put on the x and y axis
                ConstantLine xAxisConstant = constantList.getConstantLine(xAxis.getSelectedItem().toString());
                ConstantLine yAxisConstant = constantList.getConstantLine(yAxis.getSelectedItem().toString());

                //add the single values to a global values list

                Values singleValuesGlobal = new Values();

                for (int i = 0; i < constantList.getNumConstants(); i++) {

                    ConstantLine line = constantList.getConstantLine(i);

                    if (line.getTotalNumOfValues() == 1) {

                        double singleValue = Double.parseDouble(line.getSingleValue());
                        singleValuesGlobal.addValue(line.getName(), singleValue);
                    }
                }

                pGraph.setGlobalValues(singleValuesGlobal);
                pGraph.setAxisConstants(xAxis.getSelectedItem().toString(), yAxis.getSelectedItem().toString());
                pGraph.setBounds(xAxisConstant.getStartValue(), xAxisConstant.getEndValue(),
                        yAxisConstant.getStartValue(), yAxisConstant.getEndValue());

                SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        //plot the graph
                        pGraph.plot(expr.toString(), xAxis.getSelectedItem().toString(), "Function",
                                yAxis.getSelectedItem().toString());

                        //calculate the sampling rates from the step sizes as given by the user

                        int xSamples = (int) ((Double.parseDouble(xAxisConstant.getEndValue())
                                - Double.parseDouble(xAxisConstant.getStartValue()))
                                / Double.parseDouble(xAxisConstant.getStepValue()));
                        int ySamples = (int) ((Double.parseDouble(xAxisConstant.getEndValue())
                                - Double.parseDouble(xAxisConstant.getStartValue()))
                                / Double.parseDouble(xAxisConstant.getStepValue()));

                        pGraph.setSamplingRates(xSamples, ySamples);
                    }
                });

            }

            dialog.dispose();
        }
    });

    cancel.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            dialog.dispose();
        }
    });

    //add everything to the dialog show the dialog

    dialog.add(exprPanel);
    dialog.add(axisPanel);
    dialog.add(constantPanel);
    dialog.add(bottomPanel);
    dialog.setVisible(true);

}

From source file:jhplot.HChart.java

/**
 * Exports the image to some graphic format.
 *///from   w  w w .j a v  a 2 s.  c o m
protected void exportImage() {

    if (isBorderShown())
        showBorders(false);

    JFrame jm = getFrame();
    JFileChooser fileChooser = jhplot.gui.CommonGUI.openImageFileChooser(jm);

    if (fileChooser.showDialog(jm, "Save As") == 0) {

        final File scriptFile = fileChooser.getSelectedFile();
        if (scriptFile == null)
            return;
        else if (scriptFile.exists()) {
            int res = JOptionPane.showConfirmDialog(jm, "The file exists. Do you want to overwrite the file?",
                    "", JOptionPane.YES_NO_OPTION);
            if (res == JOptionPane.NO_OPTION)
                return;
        }
        String mess = "write image  file ..";
        JHPlot.showStatusBarText(mess);
        Thread t = new Thread(mess) {
            public void run() {
                export(scriptFile.getAbsolutePath());
            };
        };
        t.start();
    }

}