Example usage for java.awt AWTEvent WINDOW_EVENT_MASK

List of usage examples for java.awt AWTEvent WINDOW_EVENT_MASK

Introduction

In this page you can find the example usage for java.awt AWTEvent WINDOW_EVENT_MASK.

Prototype

long WINDOW_EVENT_MASK

To view the source code for java.awt AWTEvent WINDOW_EVENT_MASK.

Click Source Link

Document

The event mask for selecting window events.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Toolkit tk = Toolkit.getDefaultToolkit();
    final Main main = new Main();

    tk.addAWTEventListener(main, AWTEvent.WINDOW_EVENT_MASK);

    final JFrame frame = new JFrame("");
    frame.setName("your frame");
    JMenuBar mb = new JMenuBar();
    JMenu menu = new JMenu("File");
    menu.add(new AbstractAction("Quit") {
        public void actionPerformed(ActionEvent evt) {
            try {
                main.saveSettings();//from  ww w.j av  a 2  s  . c o m
                System.exit(0);
            } catch (Exception ex) {
                System.out.println(ex);
            }
        }
    });
    mb.add(menu);
    frame.setJMenuBar(mb);
    frame.pack();
    frame.setVisible(true);
}

From source file:Main.java

/** The constructor: register the event types we are interested in */
public Main() {//from  w  w  w.  j  ava2 s  . co m
    // We're interested in all types of events
    this.enableEvents(AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.KEY_EVENT_MASK
            | AWTEvent.FOCUS_EVENT_MASK | AWTEvent.COMPONENT_EVENT_MASK | AWTEvent.WINDOW_EVENT_MASK);
    this.setPreferredSize(new Dimension(500, 400));
}

From source file:EventTestPane.java

/** The constructor: register the event types we are interested in */
public EventTestPane() {
    // We're interested in all types of events
    this.enableEvents(AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.KEY_EVENT_MASK
            | AWTEvent.FOCUS_EVENT_MASK | AWTEvent.COMPONENT_EVENT_MASK | AWTEvent.WINDOW_EVENT_MASK);
    this.setPreferredSize(new Dimension(500, 400));
}

From source file:com.maxl.java.amikodesk.AMiKoDesk.java

public static void main(String[] args) {

    // Initialize globales
    m_application_data_folder = Utilities.appDataFolder();
    favorite_meds_set = new HashSet<String>();
    favorite_data = new DataStore(m_application_data_folder);
    favorite_meds_set = favorite_data.load(); // HashSet containing registration numbers

    // Register toolkit
    Toolkit tk = Toolkit.getDefaultToolkit();
    tk.addAWTEventListener(WindowSaver.getInstance(m_application_data_folder), AWTEvent.WINDOW_EVENT_MASK);

    // Specify command line options
    Options options = new Options();
    addOption(options, "help", "print this message", false, false);
    addOption(options, "version", "print the version information and exit", false, false);
    addOption(options, "port", "starts AmiKo-server at given port", true, false);
    addOption(options, "width", "sets window width", true, false);
    addOption(options, "height", "sets window height", true, false);
    addOption(options, "lang", "use given language", true, false);
    addOption(options, "type", "start light or full app", true, false);
    addOption(options, "title", "display medical info related to given title", true, false);
    addOption(options, "eancode", "display medical info related to given 13-digit ean-code", true, false);
    addOption(options, "regnr", "display medical info related to given 5-digit registration number", true,
            false);/*from  w ww . j a  va  2s .  c  om*/
    // Activate command line parser
    commandLineParse(options, args);

    // Initialize language files
    if (Utilities.appLanguage().equals("de"))
        m_rb = ResourceBundle.getBundle("amiko_de_CH", new Locale("de", "CH"));
    else if (Utilities.appLanguage().equals("fr"))
        m_rb = ResourceBundle.getBundle("amiko_fr_CH", new Locale("fr", "CH"));

    if (Utilities.appCustomization().equals("desitin")) {
        new SplashWindow(Constants.APP_NAME, 5000);
    } else if (Utilities.appCustomization().equals("meddrugs")) {
        new SplashWindow(Constants.APP_NAME, 5000);
    } else if (Utilities.appCustomization().equals("zurrose")) {
        new SplashWindow(Constants.APP_NAME, 3000);
    }
    // Load javascript
    String jscript_str = FileOps.readFromFile(Constants.JS_FOLDER + "main_callbacks.js");
    m_jscript_str = "<script language=\"javascript\">" + jscript_str + "</script>";

    // Load css style sheet
    m_css_str = "<style>" + FileOps.readFromFile(Constants.CSS_SHEET) + "</style>";

    // Load main database
    m_sqldb = new MainSqlDb();
    // Attempt to load alternative database. if db does not exist, load
    // default database
    // These databases are NEVER zipped!
    if (m_sqldb.loadDBFromPath(m_application_data_folder + "\\" + Constants.DEFAULT_AMIKO_DB_BASE
            + Utilities.appLanguage() + ".db") == 0) {
        System.out.println("Loading default amiko database");
        if (Utilities.appLanguage().equals("de"))
            m_sqldb.loadDB("de");
        else if (Utilities.appLanguage().equals("fr"))
            m_sqldb.loadDB("fr");
    }

    // Load rose database
    if (Utilities.appCustomization().equals("zurrose")) {
        m_rosedb = new RoseSqlDb();
        if (m_rosedb.loadDBFromPath(m_application_data_folder + "\\" + Constants.DEFAULT_ROSE_DB) == 0) {
            System.out.println("Loading default rose db");
            m_rosedb.loadDB();
        }
    }

    // Initialize update class
    m_maindb_update = new UpdateDb(m_sqldb);

    // Create shop folder in application data folder
    File wdir = new File(m_application_data_folder + "\\shop");
    if (!wdir.exists())
        wdir.mkdirs();

    // Load interaction cart
    m_interactions_cart = new InteractionsCart();

    // Create shopping cart and load related files
    m_shopping_cart = new ShoppingCart();
    loadAuthors();
    m_emailer = new Emailer(m_rb);

    // Create comparison cart and load related files
    m_comparison_cart = new ComparisonCart();

    // Preferences
    m_prefs = Preferences.userRoot().node(SettingsPage.class.getName());

    // UIUtils.setPreferredLookAn dFeel();
    NativeInterface.open();
    NativeSwing.initialize();

    // Setup font size based on screen size
    UIManager.getLookAndFeelDefaults().put("defaultFont", new Font("Dialog", Font.PLAIN, 14));
    UIManager.put("Label.font", new Font("Dialog", Font.PLAIN, 12));
    UIManager.put("CheckBox.font", new Font("Dialog", Font.PLAIN, 12));
    UIManager.put("Button.font", new Font("Dialog", Font.BOLD, 14));
    UIManager.put("ToggleButton.font", new Font("Dialog", Font.BOLD, 14));
    UIManager.put("ToggleButton.select", m_selected_but_color);
    UIManager.put("Menu.font", new Font("Dialog", Font.PLAIN, 12));
    UIManager.put("MenuBar.font", new Font("Dialog", Font.PLAIN, 12));
    UIManager.put("MenuItem.font", new Font("Dialog", Font.PLAIN, 12));
    UIManager.put("ToolBar.font", new Font("Dialog", Font.PLAIN, 12));

    // Schedule a job for the event-dispatching thread:
    // creating and showing this application's GUI
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            if (!commandLineOptionsProvided()) {
                System.out.println("No relevant command line options provided... creating full GUI");
                createAndShowFullGUI();
            } else if (CML_OPT_TYPE.equals("full")) {
                System.out.println("Creating full GUI");
                createAndShowFullGUI();
            } else if (CML_OPT_TYPE.equals("light")) {
                System.out.println("Creating light GUI");
                createAndShowLightGUI();
            }
        }
    });

    NativeInterface.runEventPump();
}

From source file:org.tinymediamanager.TinyMediaManager.java

/**
 * The main method./*  www .j a va  2s.  c o m*/
 * 
 * @param args
 *          the arguments
 */
public static void main(String[] args) {
    // simple parse command line
    if (args != null && args.length > 0) {
        LOGGER.debug("TMM started with: " + Arrays.toString(args));
        TinyMediaManagerCMD.parseParams(args);
        System.setProperty("java.awt.headless", "true");
    } else {
        // no cmd params found, but if we are headless - display syntax
        String head = System.getProperty("java.awt.headless");
        if (head != null && head.equals("true")) {
            LOGGER.info("TMM started 'headless', and without params -> displaying syntax ");
            TinyMediaManagerCMD.printSyntax();
            System.exit(0);
        }
    }

    // check if we have write permissions to this folder
    try {
        RandomAccessFile f = new RandomAccessFile("access.test", "rw");
        f.close();
        Files.deleteIfExists(Paths.get("access.test"));
    } catch (Exception e2) {
        String msg = "Cannot write to TMM directory, have no rights - exiting.";
        if (!GraphicsEnvironment.isHeadless()) {
            JOptionPane.showMessageDialog(null, msg);
        } else {
            System.out.println(msg);
        }
        System.exit(1);
    }

    // HACK for Java 7 and JavaFX not being in boot classpath
    // In Java 8 and on, this is installed inside jre/lib/ext
    // see http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8003171 and references
    // so we check if it is already existent in "new" directory, and if not, load it via reflection ;o)
    String dir = new File(LaunchUtil.getJVMPath()).getParentFile().getParent(); // bin, one deeper
    File jfx = new File(dir, "lib/ext/jfxrt.jar");
    if (!jfx.exists()) {
        // java 7
        jfx = new File(dir, "lib/jfxrt.jar");
        if (jfx.exists()) {
            try {
                TmmOsUtils.addPath(jfx.getAbsolutePath());
            } catch (Exception e) {
                LOGGER.debug("failed to load JavaFX - using old styles...");
            }
        }
    }

    if (Globals.isDebug()) {
        ClassLoader cl = ClassLoader.getSystemClassLoader();
        URL[] urls = ((URLClassLoader) cl).getURLs();
        LOGGER.info("=== DEBUG CLASS LOADING =============================");
        for (URL url : urls) {
            LOGGER.info(url.getFile());
        }
    }

    LOGGER.info("=====================================================");
    LOGGER.info("=== tinyMediaManager (c) 2012-2016 Manuel Laggner ===");
    LOGGER.info("=====================================================");
    LOGGER.info("tmm.version      : " + ReleaseInfo.getRealVersion());

    if (Globals.isDonator()) {
        LOGGER.info("tmm.supporter    : THANKS FOR DONATING - ALL FEATURES UNLOCKED :)");
    }

    LOGGER.info("os.name          : " + System.getProperty("os.name"));
    LOGGER.info("os.version       : " + System.getProperty("os.version"));
    LOGGER.info("os.arch          : " + System.getProperty("os.arch"));
    LOGGER.trace("network.id       : " + License.getMac());
    LOGGER.info("java.version     : " + System.getProperty("java.version"));

    if (Globals.isRunningJavaWebStart()) {
        LOGGER.info("java.webstart    : true");
    }
    if (Globals.isRunningWebSwing()) {
        LOGGER.info("java.webswing    : true");
    }

    // START character encoding debug
    debugCharacterEncoding("default encoding : ");
    System.setProperty("file.encoding", "UTF-8");
    System.setProperty("sun.jnu.encoding", "UTF-8");
    Field charset;
    try {
        // we cannot (re)set the properties while running inside JVM
        // so we trick it to reread it by setting them to null ;)
        charset = Charset.class.getDeclaredField("defaultCharset");
        charset.setAccessible(true);
        charset.set(null, null);
    } catch (Exception e) {
        LOGGER.warn("Error resetting to UTF-8", e);
    }
    debugCharacterEncoding("set encoding to  : ");
    // END character encoding debug

    // set GUI default language
    Locale.setDefault(Utils.getLocaleFromLanguage(Globals.settings.getLanguage()));
    LOGGER.info("System language  : " + System.getProperty("user.language") + "_"
            + System.getProperty("user.country"));
    LOGGER.info(
            "GUI language     : " + Locale.getDefault().getLanguage() + "_" + Locale.getDefault().getCountry());
    LOGGER.info("Scraper language : " + MovieModuleManager.MOVIE_SETTINGS.getScraperLanguage());
    LOGGER.info("TV Scraper lang  : " + TvShowModuleManager.SETTINGS.getScraperLanguage());

    // start EDT
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            boolean newVersion = !Globals.settings.isCurrentVersion(); // same snapshots/svn considered as "new", for upgrades
            try {
                Thread.setDefaultUncaughtExceptionHandler(new Log4jBackstop());
                if (!GraphicsEnvironment.isHeadless()) {
                    Thread.currentThread().setName("main");
                } else {
                    Thread.currentThread().setName("headless");
                    LOGGER.debug("starting without GUI...");
                }
                Toolkit tk = Toolkit.getDefaultToolkit();
                tk.addAWTEventListener(TmmWindowSaver.getInstance(), AWTEvent.WINDOW_EVENT_MASK);
                if (!GraphicsEnvironment.isHeadless()) {
                    setLookAndFeel();
                }
                doStartupTasks();

                // suppress logging messages from betterbeansbinding
                org.jdesktop.beansbinding.util.logging.Logger.getLogger(ELProperty.class.getName())
                        .setLevel(Level.SEVERE);

                // init ui logger
                TmmUILogCollector.init();

                LOGGER.info("=====================================================");
                // init splash
                SplashScreen splash = null;
                if (!GraphicsEnvironment.isHeadless()) {
                    splash = SplashScreen.getSplashScreen();
                }
                Graphics2D g2 = null;
                if (splash != null) {
                    g2 = splash.createGraphics();
                    if (g2 != null) {
                        Font font = new Font("Dialog", Font.PLAIN, 14);
                        g2.setFont(font);
                    } else {
                        LOGGER.debug("got no graphics from splash");
                    }
                } else {
                    LOGGER.debug("no splash found");
                }

                if (g2 != null) {
                    updateProgress(g2, "starting tinyMediaManager", 0);
                    splash.update();
                }
                LOGGER.info("starting tinyMediaManager");

                // upgrade check
                String oldVersion = Globals.settings.getVersion();
                if (newVersion) {
                    if (g2 != null) {
                        updateProgress(g2, "upgrading to new version", 10);
                        splash.update();
                    }
                    UpgradeTasks.performUpgradeTasksBeforeDatabaseLoading(oldVersion); // do the upgrade tasks for the old version
                    Globals.settings.setCurrentVersion();
                    Globals.settings.saveSettings();
                }

                // proxy settings
                if (Globals.settings.useProxy()) {
                    LOGGER.info("setting proxy");
                    Globals.settings.setProxy();
                }

                // MediaInfo /////////////////////////////////////////////////////
                if (g2 != null) {
                    updateProgress(g2, "loading MediaInfo libs", 20);
                    splash.update();
                }
                MediaInfoUtils.loadMediaInfo();

                // load modules //////////////////////////////////////////////////
                if (g2 != null) {
                    updateProgress(g2, "loading movie module", 30);
                    splash.update();
                }
                TmmModuleManager.getInstance().startUp();
                TmmModuleManager.getInstance().registerModule(MovieModuleManager.getInstance());
                TmmModuleManager.getInstance().enableModule(MovieModuleManager.getInstance());

                if (g2 != null) {
                    updateProgress(g2, "loading TV show module", 40);
                    splash.update();
                }

                TmmModuleManager.getInstance().registerModule(TvShowModuleManager.getInstance());
                TmmModuleManager.getInstance().enableModule(TvShowModuleManager.getInstance());

                if (g2 != null) {
                    updateProgress(g2, "loading plugins", 50);
                    splash.update();
                }

                // just instantiate static - will block (takes a few secs)
                PluginManager.getInstance();
                if (ReleaseInfo.isSvnBuild()) {
                    PluginManager.loadClasspathPlugins();
                }

                // do upgrade tasks after database loading
                if (newVersion) {
                    if (g2 != null) {
                        updateProgress(g2, "upgrading database to new version", 70);
                        splash.update();
                    }
                    UpgradeTasks.performUpgradeTasksAfterDatabaseLoading(oldVersion);
                }

                // launch application ////////////////////////////////////////////
                if (g2 != null) {
                    updateProgress(g2, "loading ui", 80);
                    splash.update();
                }
                if (!GraphicsEnvironment.isHeadless()) {
                    MainWindow window = new MainWindow("tinyMediaManager / " + ReleaseInfo.getRealVersion());

                    // finished ////////////////////////////////////////////////////
                    if (g2 != null) {
                        updateProgress(g2, "finished starting :)", 100);
                        splash.update();
                    }

                    // write a random number to file, to identify this instance (for
                    // updater, tracking, whatsoever)
                    Utils.trackEvent("startup");

                    TmmWindowSaver.getInstance().loadSettings(window);
                    window.setVisible(true);

                    // wizard for new user
                    if (Globals.settings.newConfig) {
                        Globals.settings.writeDefaultSettings(); // now all plugins are resolved - write again defaults!
                        TinyMediaManagerWizard wizard = new TinyMediaManagerWizard();
                        wizard.setVisible(true);
                    }

                    // show changelog
                    if (newVersion && !ReleaseInfo.getVersion().equals(oldVersion)) {
                        // special case nightly/svn: if same snapshot version, do not display changelog
                        Utils.trackEvent("updated");
                        showChangelog();
                    }
                } else {
                    TinyMediaManagerCMD.startCommandLineTasks();
                    // wait for other tmm threads (artwork download et all)
                    while (TmmTaskManager.getInstance().poolRunning()) {
                        Thread.sleep(2000);
                    }

                    LOGGER.info("bye bye");
                    // MainWindows.shutdown()
                    try {
                        // send shutdown signal
                        TmmTaskManager.getInstance().shutdown();
                        // save unsaved settings
                        Globals.settings.saveSettings();
                        // hard kill
                        TmmTaskManager.getInstance().shutdownNow();
                        // close database connection
                        TmmModuleManager.getInstance().shutDown();
                    } catch (Exception ex) {
                        LOGGER.warn(ex.getMessage());
                    }
                    System.exit(0);
                }
            } catch (IllegalStateException e) {
                LOGGER.error("IllegalStateException", e);
                if (!GraphicsEnvironment.isHeadless() && e.getMessage().contains("file is locked")) {
                    // MessageDialog.showExceptionWindow(e);
                    ResourceBundle bundle = ResourceBundle.getBundle("messages", new UTF8Control()); //$NON-NLS-1$
                    MessageDialog dialog = new MessageDialog(MainWindow.getActiveInstance(),
                            bundle.getString("tmm.problemdetected")); //$NON-NLS-1$
                    dialog.setImage(IconManager.ERROR);
                    dialog.setText(bundle.getString("tmm.nostart"));//$NON-NLS-1$
                    dialog.setDescription(bundle.getString("tmm.nostart.instancerunning"));//$NON-NLS-1$
                    dialog.setResizable(true);
                    dialog.pack();
                    dialog.setLocationRelativeTo(MainWindow.getActiveInstance());
                    dialog.setVisible(true);
                }
                System.exit(1);
            } catch (Exception e) {
                LOGGER.error("Exception while start of tmm", e);
                if (!GraphicsEnvironment.isHeadless()) {
                    MessageDialog.showExceptionWindow(e);
                }
                System.exit(1);
            }
        }

        /**
         * Update progress on splash screen.
         * 
         * @param text
         *          the text
         */
        private void updateProgress(Graphics2D g2, String text, int progress) {
            Object oldAAValue = g2.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
            g2.setComposite(AlphaComposite.Clear);
            g2.fillRect(20, 200, 480, 305);
            g2.setPaintMode();

            g2.setColor(new Color(51, 153, 255));
            g2.fillRect(22, 272, 452 * progress / 100, 21);

            g2.setColor(Color.black);
            g2.drawString(text + "...", 23, 310);
            int l = g2.getFontMetrics().stringWidth(ReleaseInfo.getRealVersion()); // bound right
            g2.drawString(ReleaseInfo.getRealVersion(), 480 - l, 325);
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, oldAAValue);
            LOGGER.debug("Startup (" + progress + "%) " + text);
        }

        /**
         * Sets the look and feel.
         * 
         * @throws Exception
         *           the exception
         */
        private void setLookAndFeel() throws Exception {
            // get font settings
            String fontFamily = Globals.settings.getFontFamily();
            try {
                // sanity check
                fontFamily = Font.decode(fontFamily).getFamily();
            } catch (Exception e) {
                fontFamily = "Dialog";
            }

            int fontSize = Globals.settings.getFontSize();
            if (fontSize < 12) {
                fontSize = 12;
            }

            String fontString = fontFamily + " " + fontSize;

            // Get the native look and feel class name
            // String laf = UIManager.getSystemLookAndFeelClassName();
            Properties props = new Properties();
            props.setProperty("controlTextFont", fontString);
            props.setProperty("systemTextFont", fontString);
            props.setProperty("userTextFont", fontString);
            props.setProperty("menuTextFont", fontString);
            // props.setProperty("windowTitleFont", "Dialog bold 20");

            fontSize = Math.round((float) (fontSize * 0.833));
            fontString = fontFamily + " " + fontSize;

            props.setProperty("subTextFont", fontString);
            props.setProperty("backgroundColor", "237 237 237");
            props.setProperty("menuBackgroundColor", "237 237 237");
            props.setProperty("controlBackgroundColor", "237 237 237");
            props.setProperty("menuColorLight", "237 237 237");
            props.setProperty("menuColorDark", "237 237 237");
            props.setProperty("toolbarColorLight", "237 237 237");
            props.setProperty("toolbarColorDark", "237 237 237");
            props.setProperty("tooltipBackgroundColor", "255 255 255");
            props.put("windowDecoration", "system");
            props.put("logoString", "");

            // Get the look and feel class name
            com.jtattoo.plaf.luna.LunaLookAndFeel.setTheme(props);
            String laf = "com.jtattoo.plaf.luna.LunaLookAndFeel";

            // Install the look and feel
            UIManager.setLookAndFeel(laf);
        }

        /**
         * Does some tasks at startup
         */
        private void doStartupTasks() {
            // rename downloaded files
            UpgradeTasks.renameDownloadedFiles();

            // extract templates, if GD has not already done
            Utils.extractTemplates();

            // check if a .desktop file exists
            if (Platform.isLinux()) {
                File desktop = new File(TmmOsUtils.DESKTOP_FILE);
                if (!desktop.exists()) {
                    TmmOsUtils.createDesktopFileForLinux(desktop);
                }
            }
        }

        private void showChangelog() {
            // read the changelog
            try {
                final String changelog = Utils.readFileToString(Paths.get("changelog.txt"));
                if (StringUtils.isNotBlank(changelog)) {
                    EventQueue.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            WhatsNewDialog dialog = new WhatsNewDialog(changelog);
                            dialog.pack();
                            dialog.setLocationRelativeTo(MainWindow.getActiveInstance());
                            dialog.setModalityType(ModalityType.APPLICATION_MODAL);
                            dialog.setVisible(true);
                        }
                    });
                }
            } catch (IOException e) {
                // no file found
                LOGGER.warn(e.getMessage());
            }
        }
    });
}

From source file:org.vpac.grisu.client.view.swing.mainPanel.Grisu.java

/**
 * Launches this application//from  w w  w  .j av a  2  s.co  m
 */
public static void main(String[] args) {

    if ((args.length > 0) && (Arrays.binarySearch(args, "--debug") >= 0)) {
        Level lvl = Level.toLevel("debug");
        Logger.getRootLogger().setLevel(lvl);
    }

    Shibboleth.initDefaultSecurityProvider();

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {

            Toolkit tk = Toolkit.getDefaultToolkit();
            tk.addAWTEventListener(WindowSaver.getInstance(), AWTEvent.WINDOW_EVENT_MASK);

            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                myLogger.debug("Could not set OS look & feel.");
            }

            try {
                CertificateFiles.copyCACerts(false);
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            myLogger.debug("Starting login dialog.");
            LoginDialog ld = new LoginDialog();
            ld.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
            ld.setVisible(true);

            if (ld.userCancelledLogin()) {
                myLogger.debug("User cancelled login dialog.");
                System.exit(0);
            }

            final Grisu application = new Grisu();
            application.serviceInterface = ld.getServiceInterface();
            myLogger.debug("Removing login dialog.");
            ld.dispose();

            myLogger.debug("Creating splash screen.");
            final LoginSplashScreen lss = new LoginSplashScreen();
            lss.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
            ApplicationStatusManager.getDefaultManager().addStatusListener(lss);
            lss.setVisible(true);

            new Thread() {
                @Override
                public void run() {
                    myLogger.debug("Creating progress bars.");

                    try {
                        application.em = new EnvironmentManager(application.serviceInterface);
                        GrisuRegistry.setServiceInterface(application.serviceInterface);
                        GrisuRegistry.setEnvironmentSnapshotValues(application.em);
                        application.em.initializeHistoryManager();
                        if (application.serviceInterface == null) {
                            myLogger.debug("Could not create/find service interface. Exiting.");
                            Utils.showErrorMessage(application.em, null, "startupError", null);
                            System.exit(1);
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        Utils.showErrorMessage(application.em, null, "startupError", e);
                        e.printStackTrace();
                        System.exit(1);
                    }

                    //            application.em.getFileManager().initAllFileSystemsInBackground();
                    //            application.em.buildInfoCacheInBackground();
                    //            application.em.getGlazedJobManagement().loadAllJobsInBackground();

                    //            ProgressDisplay pg_environment = new SwingProgressDisplay(application.getJFrame());
                    //            ProgressDisplay pg_submission = new SwingProgressDisplay(application.getJFrame());
                    ProgressDisplay pg_file_managementTransfer = new SwingProgressDisplay(
                            application.getJFrame());
                    ProgressDisplay pg_file_deletion = new SwingProgressDisplay(application.getJFrame());

                    //            EnvironmentManager.progressDisplay = pg_environment;
                    FileManagerTransferHelpers.progressDisplay = pg_file_managementTransfer;
                    FileManagerDeleteHelpers.progressDisplay = pg_file_deletion;

                    myLogger.debug("Setting application window visible.");
                    application.getJFrame().setVisible(true);

                    Thread.setDefaultUncaughtExceptionHandler(
                            new GrisuRuntimeExceptionHandler(application.getJFrame()));

                    ApplicationStatusManager.getDefaultManager().removeStatusListener(lss);
                    myLogger.debug("Removing splash screen.");
                    lss.dispose();

                    // now test whether there is a VO available
                    int availFqans = application.em.getAvailableFqans().length;
                    myLogger.debug("Number of avail Fqans: " + availFqans);
                    int usedFqans = application.em.getAllUsedFqans().size();
                    myLogger.debug("Number of used Fqans: " + usedFqans);
                    if (availFqans == 0) {
                        Utils.showErrorMessage(application.em, application.getJFrame(), "noVOs", null);
                    } else if (usedFqans == 0) {
                        Utils.showErrorMessage(application.em, application.getJFrame(), "noUsableVOs", null);
                    }

                }
            }.start();

        }
    });
}

From source file:studio.ui.Studio.java

public Studio(AppConfig config, String... args) {
    super(AppInformation.getInformation().getTitle());
    setIconImage(IconsItem.IMAGE_APP);/*from www  .ja v a 2 s  .  c o  m*/
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

    setSize((int) (0.9 * screenSize.width), (int) (0.9 * screenSize.height));
    setLocation(((int) Math.max(0, (screenSize.width - getWidth()) / 2.0)),
            (int) (Math.max(0, (screenSize.height - getHeight()) / 2.0)));

    this.studioConfig = config;

    if (studioConfig.isMaximized()) {
        setExtendedState(JFrame.MAXIMIZED_BOTH); //Maximizing the frame
    }
    addWindowStateListener(this);

    registerForMacOSXEvents();

    splitViewer = new JSplitPane();
    splitTopViewer = new JSplitPane();

    tabConsoles = new ConsolesTabbedPane();
    tabConsoles.addFireDataListener(this);
    tabEditors = new EditorsTabbedPane(tabConsoles);
    tabEditors.addFireDataListener(this);
    if (tabConsoles instanceof DataListener) {
        tabEditors.addFireDataListener((DataListener) tabConsoles);
    }
    tools = new ToolsPanel();

    splitViewer.setOrientation(JSplitPane.VERTICAL_SPLIT);
    splitViewer.setDividerSize(0);
    splitViewer.setTopComponent(splitTopViewer);
    splitViewer.setBottomComponent(tabConsoles);
    splitViewer.setOneTouchExpandable(true);

    splitTopViewer.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
    splitTopViewer.setDividerSize(9);
    splitTopViewer.setTopComponent(tools);
    splitTopViewer.setBottomComponent(tabEditors);
    splitTopViewer.setOneTouchExpandable(true);

    createConnectionsTree();
    createProjectsTree();
    rebuildMenus(null);

    getContentPane().add(splitViewer, BorderLayout.CENTER);

    splitViewer.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent event) {
            if (event.getComponent() instanceof JSplitPane) {
                if (((JSplitPane) event.getComponent()).getDividerSize() == 0) {
                    ((JSplitPane) event.getComponent()).setDividerLocation(1d);
                }
            }
        }
    });

    this.setVisible(true);
    splitTopViewer.setDividerLocation(.2d);
    splitViewer.setDividerLocation(1d);

    NewFileAction newAction = null;
    OpenFileAction openAction = null;
    ToolBarActions toolbar = appToolbar != null ? appToolbar.getToolBar("File") : null;
    if (toolbar != null) {
        for (int count = 0; count < toolbar.getComponentCount(); count++) {
            if (toolbar.getComponent(count) instanceof JButton) {
                if (((JButton) toolbar.getComponent(count)).getAction().getClass() == OpenFileAction.class) {
                    openAction = (OpenFileAction) ((JButton) toolbar.getComponent(count)).getAction();
                } else {
                    if (((JButton) toolbar.getComponent(count)).getAction().getClass() == NewFileAction.class) {
                        newAction = (NewFileAction) ((JButton) toolbar.getComponent(count)).getAction();
                    }
                }
                if (openAction != null && newAction != null) {
                    break;
                }
            }
        }
    }

    EditorFile last = null;
    if (config.getLastFiles() != null && !config.getLastFiles().isEmpty()) {
        for (EditorFile file : config.getLastFiles()) {
            if (file.isActive()) {
                last = file;
            }
            try {
                openAction.initDocument(file);
            } catch (FileException ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage(), "File", JOptionPane.WARNING_MESSAGE);
            }
        }
    } else {
        if (args == null || args.length == 0) {
            newAction.actionPerformed(null);
        }
    }
    if (args != null && args.length > 0) {
        for (String arg : args) {
            File file = new File(arg);
            if (file.exists() && file.canRead()) {
                try {
                    openAction.initDocument(new EditorFile(file));
                } catch (FileException ex) {
                    JOptionPane.showMessageDialog(this, ex.getMessage(), "File", JOptionPane.WARNING_MESSAGE);
                }
            }
        }
    }

    if (tabEditors.getTabCount() > 0) {
        if (last == null) {
            tabEditors.setSelectedIndex(0);
        } else {
            for (int count = 0; count < tabEditors.getTabCount(); count++) {
                if (tabEditors.getEditor(count).getFile().equals(last)) {
                    tabEditors.setSelectedIndex(count);
                }
            }
        }
        tabEditors.getEditor().requestFocusInWindow();
    }

    ActionBase action = new ActionBase(null, (char) 0, null, null, null, null) {
        private static final long serialVersionUID = -1752094455650906542L;

        @Override
        public void actionPerformed(ActionEvent event) {
            treeConnections.requestFocus();
        }
    };
    splitViewer.registerKeyboardAction(action, KeyStroke.getKeyStroke("F5"), JComponent.WHEN_IN_FOCUSED_WINDOW);
    splitViewer.registerKeyboardAction(action, KeyStroke.getKeyStroke("control F5"),
            JComponent.WHEN_IN_FOCUSED_WINDOW);

    action = new ActionBase(null, (char) 0, null, null, null, null) {
        private static final long serialVersionUID = -1752094455650906542L;

        @Override
        public void actionPerformed(ActionEvent event) {
            if (tabEditors.getTabCount() > 0) {
                tabEditors.requestFocus();
                tabEditors.getEditor().requestFocus();
            }
        }
    };
    splitViewer.registerKeyboardAction(action, KeyStroke.getKeyStroke("F3"), JComponent.WHEN_IN_FOCUSED_WINDOW);
    splitViewer.registerKeyboardAction(action, KeyStroke.getKeyStroke("control F3"),
            JComponent.WHEN_IN_FOCUSED_WINDOW);

    action = new ActionBase(null, (char) 0, null, null, null, null) {
        private static final long serialVersionUID = -7472441241172668338L;

        @Override
        public void actionPerformed(ActionEvent event) {
            treeProjects.requestFocus();
        }
    };
    splitViewer.registerKeyboardAction(action, KeyStroke.getKeyStroke("F6"), JComponent.WHEN_IN_FOCUSED_WINDOW);
    splitViewer.registerKeyboardAction(action, KeyStroke.getKeyStroke("control F6"),
            JComponent.WHEN_IN_FOCUSED_WINDOW);

    action = new ActionBase(null, (char) 0, null, null, null, null) {
        private static final long serialVersionUID = -1752094455650906542L;

        @Override
        public void actionPerformed(ActionEvent event) {
            if (tabConsoles.getTabCount() > 0) {
                tabConsoles.requestFocus();
                if (tabConsoles.getSelectedIndex() != -1) {
                    tabConsoles.getComponentAt(tabConsoles.getSelectedIndex()).requestFocus();
                }
            }
        }
    };
    splitViewer.registerKeyboardAction(action, KeyStroke.getKeyStroke("F4"), JComponent.WHEN_IN_FOCUSED_WINDOW);
    splitViewer.registerKeyboardAction(action, KeyStroke.getKeyStroke("control F4"),
            JComponent.WHEN_IN_FOCUSED_WINDOW);

    action = new WindowsListAction(tabEditors);
    splitViewer.registerKeyboardAction(action, action.getAccelerator(), JComponent.WHEN_IN_FOCUSED_WINDOW);
}