Example usage for javax.swing SwingUtilities invokeLater

List of usage examples for javax.swing SwingUtilities invokeLater

Introduction

In this page you can find the example usage for javax.swing SwingUtilities invokeLater.

Prototype

public static void invokeLater(Runnable doRun) 

Source Link

Document

Causes doRun.run() to be executed asynchronously on the AWT event dispatching thread.

Usage

From source file:edu.ku.brc.specify.extras.FixSQLString.java

/**
 * @param args/*from ww  w.  j av a  2s  .co m*/
 */
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @SuppressWarnings("synthetic-access")
        public void run() {
            try {
                UIHelper.OSTYPE osType = UIHelper.getOSType();
                if (osType == UIHelper.OSTYPE.Windows) {
                    UIManager.setLookAndFeel(new PlasticLookAndFeel());
                    PlasticLookAndFeel.setPlasticTheme(new ExperienceBlue());

                } else if (osType == UIHelper.OSTYPE.Linux) {
                    UIManager.setLookAndFeel(new PlasticLookAndFeel());
                }
            } catch (Exception e) {
                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DataModelClassGenerator.class, e);
                //log.error("Can't change L&F: ", e);
            }
            FixSQLString fix = new FixSQLString();
            fix.setVisible(true);

        }
    });
}

From source file:com.planetmayo.debrief.satc.util.StraightLineCullingTestForm.java

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override//  ww  w .  ja v  a  2s . com
        public void run() {
            StraightLineCullingTestForm form = new StraightLineCullingTestForm();
            form.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            form.setVisible(true);
        }
    });
}

From source file:velocitekProStartAnalyzer.MainWindow.java

/**
 * Launch the application.//from   w  w w.j  a  v a2s . c om
 */
public static void main(String[] args) {
    Locale.setDefault(Locale.ENGLISH);
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                MainWindow window = new MainWindow();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            setStartFinishMapMarkers();
        }
    });
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            defaultSize();

        }
    });
}

From source file:jboost.visualization.HistogramFrame.java

public static void main(String[] args) {

    boolean carryOver = false;

    if (args.length == 0) {
        System.out.println("Please call this from the python wrapper instead");
        System.exit(-1);/*w  w w  .  ja v a2 s .c om*/
    }

    // check carryOver flag
    if (Integer.parseInt(args[0]) != 0) {
        carryOver = true;
    }
    int offset = 1;

    // get test files
    int numTestFiles = Integer.parseInt(args[offset++]);
    String[] testFiles = new String[numTestFiles];
    if (numTestFiles == 0) {
        System.out.println("Error: Cannot find *.test.boosting.info");
        System.exit(-1);
    }
    for (int i = 0; i < numTestFiles; i++)
        testFiles[i] = args[offset + i];

    // get train files
    offset = offset + numTestFiles;
    int numTrainFiles = Integer.parseInt(args[offset++]);
    String[] trainFiles = new String[numTrainFiles];
    for (int i = 0; i < numTrainFiles; i++)
        trainFiles[i] = args[offset + i];

    // get info files
    offset = offset + numTrainFiles;
    int numInfoFiles = Integer.parseInt(args[offset++]);
    String[] infoFiles = new String[numInfoFiles];

    for (int i = 0; i < numInfoFiles; i++)
        infoFiles[i] = args[offset + i];

    // create the info parser
    infoParser = new InfoParser(testFiles, trainFiles, infoFiles, carryOver);

    SwingUtilities.invokeLater(new Runnable() {

        public void run() {
            try {
                HistogramFrame inst = new HistogramFrame();
                inst.setLocationRelativeTo(null);
                inst.setVisible(true);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (RuntimeException e) {
                e.printStackTrace();
                System.exit(-1);
            }
        }
    });
}

From source file:jfractus.app.Main.java

public static void main(String[] args) {
    createCommandLineOptions();/*from  w  ww.j  a v a  2 s.  c  om*/
    GnuParser parser = new GnuParser();
    HelpFormatter helpFormatter = new HelpFormatter();
    helpFormatter.setOptionComparator(null);

    CommandLine cmdLine = null;

    try {
        cmdLine = parser.parse(cliOptions, args);
    } catch (ParseException e) {
        System.err.println(Resources.getString("CLIParseError"));
        return;
    }

    String functionsLibPaths = cmdLine.getOptionValue("libraries");
    int threadsNum = FractusPreferencesFactory.prefs.getThreadsNumber();
    Dimension outSize = new Dimension(FractusPreferencesFactory.prefs.getDefaultImageWidth(),
            FractusPreferencesFactory.prefs.getDefaultImageHeight());
    AntialiasConfig aaConfig = FractusPreferencesFactory.prefs.getDefaultAntialiasConfig();
    boolean printProgress = cmdLine.hasOption("progress");

    try {
        String threadsNumString = cmdLine.getOptionValue("threads");
        String imageSizeString = cmdLine.getOptionValue("image-size");
        String aaMethodString = cmdLine.getOptionValue("antialias");
        String samplingSizeString = cmdLine.getOptionValue("sampling-size");

        if (functionsLibPaths != null)
            FunctionsLoaderFactory.loader.setClassPathsFromString(functionsLibPaths);

        if (aaMethodString != null) {
            if (aaMethodString.equals("none"))
                aaConfig.setMethod(AntialiasConfig.Method.NONE);
            else if (aaMethodString.equals("normal"))
                aaConfig.setMethod(AntialiasConfig.Method.NORMAL);
            else
                throw new BadValueOfArgumentException("Bad value of argument");
        }
        if (threadsNumString != null)
            threadsNum = Integer.valueOf(threadsNumString).intValue();
        if (imageSizeString != null)
            parseSize(imageSizeString, outSize);
        if (samplingSizeString != null) {
            Dimension samplingSize = new Dimension();
            parseSize(samplingSizeString, samplingSize);
            aaConfig.setSamplingSize(samplingSize.width, samplingSize.height);
        }

        if (cmdLine.hasOption("save-prefs")) {
            FunctionsLoaderFactory.loader.putClassPathsToPrefs();
            FractusPreferencesFactory.prefs.setThreadsNumber(threadsNum);
            FractusPreferencesFactory.prefs.setDefaultImageSize(outSize.width, outSize.height);
            FractusPreferencesFactory.prefs.setDefaultAntialiasConfig(aaConfig);
        }
    } catch (ArgumentParseException e) {
        System.err.println(Resources.getString("CLIParseError"));
        return;
    } catch (NumberFormatException e) {
        System.err.println(Resources.getString("CLIParseError"));
        return;
    } catch (BadValueOfArgumentException e) {
        System.err.println(Resources.getString("CLIBadValueError"));
        return;
    }

    if (cmdLine.hasOption('h') || (cmdLine.hasOption('n') && cmdLine.getArgs().length < 2)) {
        helpFormatter.printHelp(Resources.getString("CLISyntax"), cliOptions);
        return;
    }

    if (!cmdLine.hasOption('n')) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    } else {
        String[] cmdArgs = cmdLine.getArgs();
        try {
            FractalDocument fractal = new FractalDocument();
            fractal.readFromFile(new File(cmdArgs[0]));
            FractalRenderer renderer = new FractalRenderer(outSize.width, outSize.height, aaConfig, fractal);
            FractalImageWriter imageWriter = new FractalImageWriter(renderer, cmdArgs[1]);

            renderer.setThreadNumber(threadsNum);
            renderer.prepareFractal();
            if (printProgress) {
                renderer.addRenderProgressListener(new CMDLineProgressEventListener());
                imageWriter.addImageWriterProgressListener(new CMDLineImageWriteProgressListener());
            }

            imageWriter.write();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }
}

From source file:SampleTableModel.java

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

        @Override/*w w  w . j  a  va2s  . com*/
        public void run() {
            try {
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
            } catch (Exception e) {
            }

            JFrame frame = new JFrame("Swing JTable");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            JApplet applet = new SwingInterop();
            applet.init();

            frame.setContentPane(applet.getContentPane());

            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);

            //               applet.start();
        }
    });
}

From source file:sample.fa.ScriptRunnerApplication.java

public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> {
        ScriptRunnerApplication app = new ScriptRunnerApplication();
        app.createGUI();//from   w  w  w  . j a  va  2s . com
        if (args.length > 0) {
            File f = new File(args[0]);
            if (f.isFile()) {
                app.loadScript(f);
            }
        }
    });
}

From source file:components.JWSFileChooserDemo.java

public static void main(String[] args) {
    //Schedule a job for the event dispatch thread:
    //creating and showing this application's GUI.
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            //Turn off metal's use of bold fonts
            UIManager.put("swing.boldMetal", Boolean.FALSE);
            createAndShowGUI();//ww w  .j  a va  2s  . c o  m
        }
    });
}

From source file:components.TextAreaDemo.java

public static void main(String args[]) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            //Turn off metal's use of bold fonts
            UIManager.put("swing.boldMetal", Boolean.FALSE);
            new TextAreaDemo().setVisible(true);
        }//from  w w  w  .j  a v a 2s  .  co m
    });
}

From source file:com.edduarte.protbox.Protbox.java

public static void main(String... args) {

    // activate debug / verbose mode
    if (args.length != 0) {
        List<String> argsList = Arrays.asList(args);
        if (argsList.contains("-v")) {
            Constants.verbose = true;//from w  w w  . j  a v  a  2 s. com
        }
    }

    // use System's look and feel
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception ex) {
        // If the System's look and feel is not obtainable, continue execution with JRE look and feel
    }

    // check this is a single instance
    try {
        new ServerSocket(1882);
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null,
                "Another instance of Protbox is already running.\n" + "Please close the other instance first.",
                "Protbox already running", JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }

    // check if System Tray is supported by this operative system
    if (!SystemTray.isSupported()) {
        JOptionPane.showMessageDialog(null,
                "Your operative system does not support system tray functionality.\n"
                        + "Please try running Protbox on another operative system.",
                "System tray not supported", JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }

    // add PKCS11 providers
    FileFilter fileFilter = new AndFileFilter(new WildcardFileFilter(Lists.newArrayList("*.config")),
            HiddenFileFilter.VISIBLE);

    File[] providersConfigFiles = new File(Constants.PROVIDERS_DIR).listFiles(fileFilter);

    if (providersConfigFiles != null) {
        for (File f : providersConfigFiles) {
            try {
                List<String> lines = FileUtils.readLines(f);
                String aliasLine = lines.stream().filter(line -> line.contains("alias")).findFirst().get();
                lines.remove(aliasLine);
                String alias = aliasLine.split("=")[1].trim();

                StringBuilder sb = new StringBuilder();
                for (String s : lines) {
                    sb.append(s);
                    sb.append("\n");
                }

                Provider p = new SunPKCS11(new ReaderInputStream(new StringReader(sb.toString())));
                Security.addProvider(p);

                pkcs11Providers.put(p.getName(), alias);

            } catch (IOException | ProviderException ex) {
                if (ex.getMessage().equals("Initialization failed")) {
                    ex.printStackTrace();

                    String s = "The following error occurred:\n" + ex.getCause().getMessage()
                            + "\n\nIn addition, make sure you have "
                            + "an available smart card reader connected before opening the application.";
                    JTextArea textArea = new JTextArea(s);
                    textArea.setColumns(60);
                    textArea.setLineWrap(true);
                    textArea.setWrapStyleWord(true);
                    textArea.setSize(textArea.getPreferredSize().width, 1);

                    JOptionPane.showMessageDialog(null, textArea, "Error loading PKCS11 provider",
                            JOptionPane.ERROR_MESSAGE);
                    System.exit(1);
                } else {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(null,
                            "Error while setting up PKCS11 provider from configuration file " + f.getName()
                                    + ".\n" + ex.getMessage(),
                            "Error loading PKCS11 provider", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }

    // adds a shutdown hook to save instantiated directories into files when the application is being closed
    Runtime.getRuntime().addShutdownHook(new Thread(Protbox::exit));

    // get system tray and run tray applet
    tray = SystemTray.getSystemTray();
    SwingUtilities.invokeLater(() -> {

        if (Constants.verbose) {
            logger.info("Starting application");
        }

        //Start a new TrayApplet object
        trayApplet = TrayApplet.getInstance();
    });

    // prompts the user to choose which provider to use
    ProviderListWindow.showWindow(Protbox.pkcs11Providers.keySet(), providerName -> {

        // loads eID token
        eIDTokenLoadingWindow.showPrompt(providerName, (returnedUser, returnedCertificateData) -> {
            user = returnedUser;
            certificateData = returnedCertificateData;

            // gets a password to use on the saved registry files (for loading and saving)
            final AtomicReference<Consumer<SecretKey>> consumerHolder = new AtomicReference<>(null);
            consumerHolder.set(password -> {
                registriesPasswordKey = password;
                try {
                    // if there are serialized files, load them if they can be decoded by this user's private key
                    final List<SavedRegistry> serializedDirectories = new ArrayList<>();
                    if (Constants.verbose) {
                        logger.info("Reading serialized registry files...");
                    }

                    File[] registryFileList = new File(Constants.REGISTRIES_DIR).listFiles();
                    if (registryFileList != null) {
                        for (File f : registryFileList) {
                            if (f.isFile()) {
                                byte[] data = FileUtils.readFileToByteArray(f);
                                try {
                                    Cipher cipher = Cipher.getInstance("AES");
                                    cipher.init(Cipher.DECRYPT_MODE, registriesPasswordKey);
                                    byte[] registryDecryptedData = cipher.doFinal(data);
                                    serializedDirectories.add(new SavedRegistry(f, registryDecryptedData));
                                } catch (GeneralSecurityException ex) {
                                    if (Constants.verbose) {
                                        logger.info("Inserted Password does not correspond to " + f.getName());
                                    }
                                }
                            }
                        }
                    }

                    // if there were no serialized directories, show NewDirectory window to configure the first folder
                    if (serializedDirectories.isEmpty() || registryFileList == null) {
                        if (Constants.verbose) {
                            logger.info("No registry files were found: running app as first time!");
                        }
                        NewRegistryWindow.start(true);

                    } else { // there were serialized directories
                        loadRegistry(serializedDirectories);
                        trayApplet.repaint();
                        showTrayApplet();
                    }

                } catch (AWTException | IOException | GeneralSecurityException | ReflectiveOperationException
                        | ProtboxException ex) {

                    JOptionPane.showMessageDialog(null,
                            "The inserted password was invalid! Please try another one!", "Invalid password!",
                            JOptionPane.ERROR_MESSAGE);
                    insertPassword(consumerHolder.get());
                }
            });
            insertPassword(consumerHolder.get());
        });
    });
}