Example usage for javax.swing JOptionPane DEFAULT_OPTION

List of usage examples for javax.swing JOptionPane DEFAULT_OPTION

Introduction

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

Prototype

int DEFAULT_OPTION

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

Click Source Link

Document

Type meaning Look and Feel should not supply any options -- only use the options from the JOptionPane.

Usage

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

/**
 * //from ww  w  .j  a  va2 s .c  om
 */
protected void showForm() {
    //boolean isParentNew = parentObj instanceof FormDataObjIFace ? ((FormDataObjIFace)parentObj).getId() == null : false;
    boolean isNewObject = MultiView.isOptionOn(options, MultiView.IS_NEW_OBJECT);
    boolean isEdit = MultiView.isOptionOn(options, MultiView.IS_EDITTING) || isNewObject;

    String closeBtnTitle = isEdit ? getResourceString("DONE") : getResourceString("CLOSE");

    ViewBasedDisplayDialog dlg = new ViewBasedDisplayDialog((Frame) UIRegistry.getTopWindow(),
            subviewDef.getViewSetName(), subviewDef.getViewName(), null, // What is this argument???
            frameTitle, closeBtnTitle, view.getClassName(), cellName, // idFieldName
            isEdit | isNewObject, false, cellName, mvParent,
            options | MultiView.HIDE_SAVE_BTN | MultiView.DONT_ADD_ALL_ALTVIEWS
                    | MultiView.USE_ONLY_CREATION_MODE,
            CustomDialog.CANCEL_BTN | (StringUtils.isNotEmpty(helpContext) ? CustomDialog.HELP_BTN : 0)) {

        /* (non-Javadoc)
         * @see edu.ku.brc.ui.db.ViewBasedDisplayDialog#cancelButtonPressed()
         */
        @Override
        protected void cancelButtonPressed() {
            multiView.aboutToShutdown();

            FormViewObj fvo = multiView.getCurrentViewAsFormViewObj();
            if (fvo != null) {
                FormValidator validator = multiView.getCurrentValidator();
                if (validator != null && validator.getState() != UIValidatable.ErrorType.Valid) {
                    boolean isNew = fvo.isNewlyCreatedDataObj();
                    String msgKey = isNew ? "MV_INCOMPLETE_DATA_NEW" : "MV_INCOMPLETE_DATA";
                    String btnKey = isNew ? "MV_REMOVE_ITEM" : "MV_DISCARD_ITEM";
                    Object[] optionLabels = { getResourceString(btnKey), getResourceString("CANCEL") };
                    int rv = JOptionPane.showOptionDialog(UIRegistry.getMostRecentWindow(),
                            getResourceString(msgKey), getResourceString("MV_INCOMPLETE_DATA_TITLE"),
                            JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, optionLabels,
                            optionLabels[0]);
                    if (rv == JOptionPane.NO_OPTION) {
                        return;
                    }
                }
            }
            super.cancelButtonPressed();
        }

    };

    dlg.setHelpContext("SUBVIEW_FORM_HELP");

    dlg.setCancelLabel(closeBtnTitle);
    frame = dlg;
    multiView = frame.getMultiView();

    // Only get the data from the parent the first time.
    if (parentObj != null && dataObj == null) {
        DataProviderSessionIFace sessionLocal = null;
        try {
            DataObjectGettable getter = DataObjectGettableFactory.get(parentObj.getClass().getName(),
                    FormHelper.DATA_OBJ_GETTER);
            sessionLocal = parentObj.getId() != null ? DataProviderFactory.getInstance().createSession() : null;

            // rods - 07/22/08 - Apparently Merge just doesn't work the way it seems it should
            // so instead we will just go get the parent again.
            if (parentObj.getId() != null) {
                parentObj = (FormDataObjIFace) sessionLocal.get(parentObj.getDataClass(), parentObj.getId());
            }

            Object[] objs = UIHelper.getFieldValues(subviewDef, parentObj, getter);
            if (objs == null) {
                try {
                    Class<?> cls = Class.forName(view.getClassName());
                    if (FormDataObjIFace.class.isAssignableFrom(cls)) {
                        dataObj = cls.newInstance();
                        ((FormDataObjIFace) dataObj).initialize();
                        parentObj.addReference((FormDataObjIFace) dataObj, subviewDef.getName());
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SubViewBtn.class, ex);
                }

            } else {
                dataObj = objs[0];
            }
            multiView.setParentDataObj(parentObj);
            multiView.setData(dataObj);
            CommandDispatcher.dispatch(new CommandAction("Data_Entry", "SHOW_SUBVIEW",
                    new Pair<Object, Object>(parentObj, dataObj)));

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

        } finally {
            if (sessionLocal != null) {
                sessionLocal.close();
            }
        }
    } else {
        multiView.setParentDataObj(parentObj);
        DataProviderSessionIFace sessionLocal = null;
        try {
            sessionLocal = DataProviderFactory.getInstance().createSession();
            multiView.setSession(sessionLocal);
            if (dataObj instanceof Set<?>) {
                for (Object obj : ((Set<?>) dataObj)) {
                    if (obj instanceof FormDataObjIFace && ((FormDataObjIFace) obj).getId() != null) {
                        sessionLocal.attach(obj);
                    }

                }
            } else if (dataObj instanceof FormDataObjIFace && ((FormDataObjIFace) dataObj).getId() != null) {
                sessionLocal.attach(dataObj);
            }
            multiView.setData(dataObj);
            multiView.setSession(null);

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            sessionLocal.close();
        }
    }

    multiView.setClassToCreate(classToCreate);

    FormValidator formVal = null;
    if (multiView.getCurrentViewAsFormViewObj() != null) {
        formVal = multiView.getCurrentViewAsFormViewObj().getValidator();
        if (formVal != null) {
            formVal.setEnabled(true);
            multiView.addCurrentValidator();
            if (multiView.getCurrentViewAsFormViewObj() != null) {
                final ResultSetController rsc = multiView.getCurrentViewAsFormViewObj().getRsController();
                if (rsc != null && rsc.getNewRecBtn() != null) {
                    rsc.getNewRecBtn().setEnabled(true);
                    /*if (rsc.getLength() == 0)
                    {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run()
                        {
                            //rsc.getNewRecBtn().doClick();
                        }
                    });
                    }*/
                }
            }
        }
    }

    dlg.createUI();
    frame.getCancelBtn().setEnabled(true);

    frame.showDisplay(true);

    if (formVal != null) {
        multiView.removeCurrentValidator();
    }

    FormViewObj fvo = null;
    if (multiView != null) {
        if (frame.isEditMode()) {
            frame.getMultiView().getDataFromUI();
            FormViewObj.traverseToGetDataFromForms(frame.getMultiView());

            updateBtnText();

            mvParent.getCurrentValidator().validateRoot();
        }
    } else {

    }

    CommandDispatcher.dispatch(new CommandAction("Data_Entry", "CLOSE_SUBVIEW",
            new Triple<Object, Object, Object>(fvo, parentObj, dataObj)));

    frame.dispose();
    frame = null;
}

From source file:com.raceup.fsae.test.TesterGui.java

/**
 * Shows dialog with info about unsuccessful test submission
 *//*w w  w.j a v a 2 s. c o m*/
private void showUnSuccessfulTestSubmissionDialog() {
    totalTestTimer.start(); // re-start total timer

    String message = test.toString();
    message += "\nDon't worry, be happy: this box will automatically " + "close after "
            + Integer.toString(SECONDS_WAIT_BETWEEN_SUBMISSIONS) + " seconds of your " + "submission.\nEnjoy.";

    JOptionPane opt = new JOptionPane(message, JOptionPane.WARNING_MESSAGE, JOptionPane.DEFAULT_OPTION, null,
            new Object[] {}); // no buttons
    final JDialog dlg = opt.createDialog("Error");
    new Thread(() -> {
        try {
            Thread.sleep(SECONDS_WAIT_BETWEEN_SUBMISSIONS * 1000);
            dlg.dispose();
        } catch (Throwable t) {
            System.err.println(t.toString());
        }
    }).start();
    dlg.setVisible(true);
}

From source file:ca.sqlpower.architect.swingui.enterprise.SecurityPanel.java

private User createUserFromPrompter() {
    JTextField nameField = new JTextField(15);
    JTextField passField = new JPasswordField(15);
    JTextField confirmField = new JPasswordField(15);

    JPanel namePanel = new JPanel(new BorderLayout());
    namePanel.add(new JLabel("User Name"), BorderLayout.WEST);
    namePanel.add(nameField, BorderLayout.EAST);

    JPanel passPanel = new JPanel(new BorderLayout());
    passPanel.add(new JLabel("Password"), BorderLayout.WEST);
    passPanel.add(passField, BorderLayout.EAST);

    JPanel confirmPanel = new JPanel(new BorderLayout());
    confirmPanel.add(new JLabel("Confirm Password"), BorderLayout.WEST);
    confirmPanel.add(confirmField, BorderLayout.EAST);

    Object[] messages = new Object[] { "Specify the User's Name and Password.", namePanel, passPanel,
            confirmPanel };/*w  w  w.j  a  v  a2  s .c  o m*/

    String[] options = { "OK", "Cancel", };
    int option = JOptionPane.showOptionDialog(getPanel(), messages, "Specify the User's Name and Password",
            JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);

    if (nameField.getText().equals("") || nameField.getText() == null || passField.getText().equals("")
            || passField.getText() == null) {
        return null;
    }

    if (!passField.getText().equals(confirmField.getText())) {
        JOptionPane.showMessageDialog(getPanel(), "The passwords you entered do not match.", "Error",
                JOptionPane.ERROR_MESSAGE);
        return null;
    }

    User user = null;
    if (option == 0) {
        String password;
        try {
            password = new String(Hex.encodeHex(digester.digest(passField.getText().getBytes("UTF-8"))));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Unable to encode password", e);
        }
        user = new User(nameField.getText(), password);
    }

    return user;
}

From source file:esmska.gui.AboutFrame.java

private void creditsButtonActionPerformed(ActionEvent evt) {//GEN-FIRST:event_creditsButtonActionPerformed
    //show credits
    try {//  w  ww  .  ja  v a  2  s  .  c  om
        logger.fine("Showing credits...");
        String credits = IOUtils.toString(getClass().getResourceAsStream(RES + "credits.html"), "UTF-8");
        String translators = l10n.getString("Translators");
        if ("translator-credits".equals(translators)) {
            //there are no translators mentioned
            translators = "";
        } else {
            translators = translators.replaceAll("\n", "<br>\n").replaceAll("\n  ", "\n&nbsp;&nbsp;");
            //add hyperlinks to the Launchpad URLs
            translators = translators.replaceAll("(https://[^<]*)", "<a href=\"$1\">$1</a>");
        }

        String document = MessageFormat.format(credits, l10n.getString("Credits.authors"),
                l10n.getString("Credits.contributors"), l10n.getString("Credits.graphics"),
                l10n.getString("Credits.sponsors"), l10n.getString("Credits.translators"), translators,
                Links.DONATORS, l10n.getString("Credits.moreDonators"),
                MessageFormat.format(l10n.getString("Credits.packagers"), Links.DOWNLOAD));

        JTextPane tp = new JTextPane();
        tp.setContentType("text/html; charset=UTF-8");
        tp.setText(document);
        tp.setEditable(false);
        tp.setPreferredSize(new Dimension(450, 400));
        tp.setCaretPosition(0);
        //make links clickable
        tp.addHyperlinkListener(new HyperlinkListener() {
            @Override
            public void hyperlinkUpdate(final HyperlinkEvent e) {
                if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED && Desktop.isDesktopSupported()) {
                    try {
                        logger.fine("Browsing URL: " + e.getURL());
                        Desktop.getDesktop().browse(e.getURL().toURI());
                    } catch (Exception ex) {
                        logger.log(Level.SEVERE, "Can't browse hyperlink: " + e.getURL(), ex);
                    }
                }
            }
        });

        String option = l10n.getString("AboutFrame.Thank_you");
        JOptionPane op = new JOptionPane(new JScrollPane(tp), JOptionPane.INFORMATION_MESSAGE,
                JOptionPane.DEFAULT_OPTION, null, new Object[] { option }, option);
        JDialog dialog = op.createDialog(this, l10n.getString("AboutFrame.Credits"));
        dialog.setResizable(true);
        dialog.pack();
        dialog.setVisible(true);
    } catch (IOException e) {
        logger.log(Level.WARNING, "Could not show credits", e);
    }
}

From source file:net.chaosserver.timelord.swingui.CommonTaskPanel.java

/**
 * Shows a dialog the gives the user the option to hide a task
 * that has not been written to for a long time.
 *
 * @param taskName the name of the task to prompt the user to hide
 * @param lastInputDate the last date the user added time to the task
 *
 * @return Either (0) for hiding the task or (1) for continuing to show
 *///from  ww w .j a v a  2s. c  om
protected int showHideTaskDialog(String taskName, Date lastInputDate) {
    int result;

    String hideTask = "Hide Task";
    String ignore = "Ignore";
    Object[] options = { hideTask, ignore };

    result = JOptionPane.showOptionDialog(null,
            "No time has been tracked to the task [" + taskName + "] since ["
                    + DateUtil.BASIC_DATE_FORMAT.format(lastInputDate) + "].  Do you wish to hide it?",

            "Hide Very Old Task", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
            hideTask);

    return result;
}

From source file:com.atlauncher.data.Settings.java

public void loadEverything() {
    setupServers(); // Setup the servers available to use in the Launcher
    findActiveServers(); // Find active servers
    loadServerProperty(false); // Get users Server preference
    if (hasUpdatedFiles()) {
        downloadUpdatedFiles(); // Downloads updated files on the server
    }//from   w ww.  j a  v a2  s.  com

    checkForLauncherUpdate();

    downloadExternalLibraries();

    if (!Utils.checkAuthLibLoaded()) {
        LogManager.error("AuthLib was not loaded into the classpath!");
    }

    loadNews(); // Load the news

    this.languageLoaded = true; // Languages are now loaded

    loadMinecraftVersions(); // Load info about the different Minecraft versions

    loadPacks(); // Load the Packs available in the Launcher

    loadUsers(); // Load the Testers and Allowed Players for the packs

    loadInstances(); // Load the users installed Instances

    loadAccounts(); // Load the saved Accounts

    loadCheckingServers(); // Load the saved servers we're checking with the tool

    loadProperties(); // Load the users Properties

    if (this.isUsingCustomJavaPath()) {
        checkForValidJavaPath(true); // Checks for a valid Java path
    }

    console.setupLanguage(); // Setup language on the console

    clearOldLogs(); // Clear all the old logs out

    checkResources(); // Check for new format of resources

    checkAccountUUIDs(); // Check for accounts UUID's and add them if necessary

    LogManager.debug("Checking for access to master server");
    OUTER: for (Pack pack : this.packs) {
        if (pack.isTester()) {
            for (Server server : this.servers) {
                if (server.getName().equals("Master Server (Testing Only)")) {
                    server.setUserSelectable(true);
                    LogManager.debug("Access to master server granted");
                    break OUTER; // Don't need to check anymore so break the outer loop
                }
            }
        }
    }
    LogManager.debug("Finished checking for access to master server");

    loadServerProperty(true); // Get users Server preference

    if (Utils.isWindows() && this.javaPath.contains("x86")) {
        LogManager.warn("You're using 32 bit Java on a 64 bit Windows install!");
        String[] options = { Language.INSTANCE.localize("common.yes"),
                Language.INSTANCE.localize("common.no") };
        int ret = JOptionPane.showOptionDialog(App.settings.getParent(),
                HTMLUtils.centerParagraph(
                        Language.INSTANCE.localizeWithReplace("settings.running32bit", "<br/><br/>")),
                Language.INSTANCE.localize("settings.running32bittitle"), JOptionPane.DEFAULT_OPTION,
                JOptionPane.ERROR_MESSAGE, null, options, options[0]);
        if (ret == 0) {
            Utils.openBrowser("http://www.atlauncher.com/help/32bit/");
            System.exit(0);
        }
    }

    if (!Utils.isJava7OrAbove(true) && !this.hideOldJavaWarning) {
        LogManager.warn("You're using an old unsupported version of Java (Java 6 or older)!");
        String[] options = { Language.INSTANCE.localize("common.download"),
                Language.INSTANCE.localize("common" + ".ok"),
                Language.INSTANCE.localize("instance" + "" + ".dontremindmeagain") };
        int ret = JOptionPane.showOptionDialog(App.settings.getParent(),
                HTMLUtils.centerParagraph(
                        Language.INSTANCE.localizeWithReplace("settings.unsupportedjava", "<br/><br/>")),
                Language.INSTANCE.localize("settings.unsupportedjavatitle"), JOptionPane.DEFAULT_OPTION,
                JOptionPane.ERROR_MESSAGE, null, options, options[0]);
        if (ret == 0) {
            Utils.openBrowser("http://atl.pw/java7download");
            System.exit(0);
        } else if (ret == 2) {
            this.hideOldJavaWarning = true;
            this.saveProperties();
        }
    }

    if (this.advancedBackup) {
        dropbox = new DropboxSync();
    }

    if (!this.hadPasswordDialog) {
        checkAccounts(); // Check accounts with stored passwords
    }

    if (this.enableServerChecker) {
        this.startCheckingServers();
    }
}

From source file:net.pms.newgui.LanguageSelection.java

private JComponent buildComponent() {
    // UIManager manages to get the background color wrong for text
    // components on OS X, so we apply the color manually
    Color backgroundColor = UIManager.getColor("Panel.background");
    rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.PAGE_AXIS));

    // It needs to be something in the title text, or the size calculation for the border will be wrong.
    selectionPanelBorder.setTitle(" ");
    selectionPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5),
            BorderFactory.createCompoundBorder(selectionPanelBorder,
                    BorderFactory.createEmptyBorder(10, 5, 10, 5))));
    selectionPanel.setLayout(new BoxLayout(selectionPanel, BoxLayout.PAGE_AXIS));
    descriptionText.setEditable(false);/*from w  w w  . j a  v a 2s  .  co m*/
    descriptionText.setBackground(backgroundColor);
    descriptionText.setFocusable(false);
    descriptionText.setLineWrap(true);
    descriptionText.setWrapStyleWord(true);
    descriptionText.setBorder(BorderFactory.createEmptyBorder(5, 15, 10, 15));
    selectionPanel.add(descriptionText);

    jLanguage = new JComboBox<>(keyedModel);
    jLanguage.setEditable(false);
    jLanguage.setPreferredSize(new Dimension(50, jLanguage.getPreferredSize().height));
    jLanguage.addActionListener(new LanguageComboBoxActionListener());
    languagePanel.setLayout(new BoxLayout(languagePanel, BoxLayout.PAGE_AXIS));
    languagePanel.setBorder(BorderFactory.createEmptyBorder(5, 15, 5, 15));
    languagePanel.add(jLanguage);
    selectionPanel.add(languagePanel);

    warningText.setEditable(false);
    warningText.setFocusable(false);
    warningText.setBackground(backgroundColor);
    warningText.setFont(warningText.getFont().deriveFont(Font.BOLD));
    warningText.setLineWrap(true);
    warningText.setWrapStyleWord(true);
    warningText.setBorder(BorderFactory.createEmptyBorder(5, 15, 0, 15));
    selectionPanel.add(warningText);

    // It needs to be something in the title text, or the size calculation for the border will be wrong.
    infoTextBorder.setTitle(" ");
    infoText.setBorder(
            BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5), BorderFactory
                    .createCompoundBorder(infoTextBorder, BorderFactory.createEmptyBorder(15, 20, 20, 20))));
    infoText.setEditable(false);
    infoText.setFocusable(false);
    infoText.setBackground(backgroundColor);
    infoText.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);

    // This exercise is to avoid using the default shared StyleSheet with padding
    CustomHTMLEditorKit editorKit = new CustomHTMLEditorKit();
    StyleSheet styleSheet = new StyleSheet();
    styleSheet.addRule("a { color: #0000EE; text-decoration:underline; }");
    editorKit.setStyleSheet(styleSheet);
    infoText.setEditorKit(editorKit);
    infoText.addHyperlinkListener(new HyperlinkListener() {

        @Override
        public void hyperlinkUpdate(HyperlinkEvent e) {
            if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                boolean error = false;
                if (Desktop.isDesktopSupported()) {
                    try {
                        Desktop.getDesktop().browse(new URI(e.getDescription()));
                    } catch (IOException | URISyntaxException ex) {
                        LOGGER.error("Language selection failed to open translation page hyperlink: ",
                                ex.getMessage());
                        LOGGER.trace("", ex);
                        error = true;
                    }
                } else {
                    LOGGER.warn("Desktop is not supported, the clicked translation page link can't be opened");
                    error = true;
                }
                if (error) {
                    JOptionPane.showOptionDialog(dialog,
                            String.format(buildString("LanguageSelection.6", true), PMS.CROWDIN_LINK),
                            buildString("Dialog.Error"), JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE,
                            null, null, null);
                }
            }
        }

    });

    rootPanel.add(selectionPanel);
    rootPanel.add(infoText);

    applyButton.addActionListener(new ApplyButtonActionListener());
    applyButton.setActionCommand("apply");

    selectButton.addActionListener(new SelectButtonActionListener());
    selectButton.setActionCommand("select");

    return rootPanel;

}

From source file:ca.sqlpower.architect.swingui.enterprise.SecurityPanel.java

private boolean promptForDelete(SPObject obj) {

    String typeString = "";
    if (obj instanceof User) {
        typeString = "User";
    }//from   w ww  .  ja va 2s . c o m
    if (obj instanceof Group) {
        typeString = "Group";
    }

    Object[] options = { "Yes", "No" };

    int option = JOptionPane.showOptionDialog(null,
            new Object[] {
                    "Are you sure you want to delete the " + typeString + " \"" + obj.getName() + "\"?" },
            "", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);

    if (option == 0) {
        return true;
    }

    return false;
}

From source file:com.atlauncher.data.Settings.java

public void checkAccounts() {
    boolean matches = false;
    if (this.accounts != null || this.accounts.size() >= 1) {
        for (Account account : this.accounts) {
            if (account.isRemembered()) {
                matches = true;/*from w  w  w . j  a  va 2s .  co m*/
            }
        }
    }
    if (matches) {
        String[] options = { Language.INSTANCE.localize("common.ok"),
                Language.INSTANCE.localize("account" + "" + ".removepasswords") };
        int ret = JOptionPane.showOptionDialog(App.settings.getParent(),
                HTMLUtils.centerParagraph(
                        Language.INSTANCE.localizeWithReplace("account.securitywarning", "<br/>")),
                Language.INSTANCE.localize("account.securitywarningtitle"), JOptionPane.DEFAULT_OPTION,
                JOptionPane.ERROR_MESSAGE, null, options, options[0]);
        if (ret == 1) {
            for (Account account : this.accounts) {
                if (account.isRemembered()) {
                    account.setRemember(false);
                }
            }
            this.saveAccounts();
        }
    }
    this.saveProperties();
}

From source file:net.chaosserver.timelord.swingui.Timelord.java

/**
 * Starts up the timelord application and displays the frame.
 *///from  www.  j av a  2s  .  com
public void start() {
    applicationFrame = new JFrame("Timelord");

    // Get the pretty application icon
    URL iconUrl = this.getClass().getResource("/net/chaosserver/timelord/TimelordIcon.gif");

    if (log.isTraceEnabled()) {
        log.trace("iconUrl is [" + iconUrl + "]");
    }

    if (iconUrl != null) {
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Image applicationImage = toolkit.getImage(iconUrl);
        applicationIcon = new ImageIcon(applicationImage);
        applicationFrame.setIconImage(applicationImage);
    } else {
        if (log.isWarnEnabled()) {
            log.warn("Cound not find icon url");
        }
    }

    if (!isAlreadyRunning() && !isUpgradeRequested()) {
        TimelordMenu menu = new TimelordMenu(this);
        applicationFrame.setJMenuBar(menu);
        applicationFrame.addWindowListener(new WindowCloser());

        if (OsUtil.isMac()) {
            try {
                Class<?> macSwingerClass = Class
                        .forName("net.chaosserver.timelord." + "swingui.macos.MacSwinger");

                Constructor<?> macSwingerConstructor = macSwingerClass
                        .getConstructor(new Class[] { Timelord.class });

                macSwingerConstructor.newInstance(new Object[] { this });
            } catch (Exception e) {
                // Shouldn't happen, but not a big deal
                if (log.isWarnEnabled()) {
                    log.warn("Failed to create the MacSwinger", e);
                }
            }

        }

        TimelordDataReaderWriter timelordDataRW = new XmlDataReaderWriter();

        try {
            TimelordData inputTimelordData = timelordDataRW.readTimelordData();
            inputTimelordData.cleanse();
            inputTimelordData.resetTaskListeners();
            setTimelordData(inputTimelordData);
            menu.setTimelordData(getTimelordData());

            applicationFrame.setSize(loadLastFrameSize());
            timelordTabbedPane = new TimelordTabbedPane(getTimelordData());
            applicationFrame.getContentPane().add(timelordTabbedPane);

            applicationFrame.setLocation(loadLastFrameLocation());
            applicationFrame.setVisible(true);

            // If there is no data for Today, let the user set the
            // start time.
            TimelordDayView timelordDayView = new TimelordDayView(inputTimelordData,
                    DateUtil.trunc(new Date()));

            if (timelordDayView.getTotalTimeToday(true) == 0) {
                menu.timelord.changeStartTime(true);
            }

            bringToFrontThread = new BringToFrontThread(applicationFrame, this);
            bringToFrontThread.start();

            autoSaveThread = new AutoSaveThread(getTimelordData());
            autoSaveThread.start();
        } catch (TimelordDataException e) {
            String shutdown = "Shutdown";
            Object[] options = { shutdown };

            JOptionPane.showOptionDialog(null, "There was an unrecoverable error trying to load "
                    + "the file.\nTimelord was probably shutdown " + "in the middle of the last write.\nThere "
                    + "should be a lot of backup files inside the "
                    + "defaut location.\nCopy one of the backups "
                    + "over the most recent, restart, and keep your " + "fingers crossed.\n" + e,
                    "Timelord Data File Corrupted", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null,
                    options, shutdown);

            stop();
        }
    } else {
        stop();
    }
}