Example usage for javax.swing UIManager getSystemLookAndFeelClassName

List of usage examples for javax.swing UIManager getSystemLookAndFeelClassName

Introduction

In this page you can find the example usage for javax.swing UIManager getSystemLookAndFeelClassName.

Prototype

public static String getSystemLookAndFeelClassName() 

Source Link

Document

Returns the name of the LookAndFeel class that implements the native system look and feel if there is one, otherwise the name of the default cross platform LookAndFeel class.

Usage

From source file:Main.java

public static void main(String args[]) {

    try {//from  w ww. ja va  2s .  c o m
        String cn = UIManager.getSystemLookAndFeelClassName();
        UIManager.setLookAndFeel(cn); // Use the native L&F
    } catch (Exception cnf) {
    }
    PrinterJob job = PrinterJob.getPrinterJob();
    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    PageFormat pf = job.pageDialog(aset);
    job.setPrintable(new Main(), pf);
    boolean ok = job.printDialog(aset);
    if (ok) {
        try {
            job.print(aset);
        } catch (PrinterException ex) {
            /* The job did not successfully complete */
        }
    }
    System.exit(0);
}

From source file:PrintDialogExample.java

public static void main(String args[]) {

    try {/*from  w  w  w.ja  v  a 2 s.co m*/
        String cn = UIManager.getSystemLookAndFeelClassName();
        UIManager.setLookAndFeel(cn); // Use the native L&F
    } catch (Exception cnf) {
    }
    PrinterJob job = PrinterJob.getPrinterJob();
    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    PageFormat pf = job.pageDialog(aset);
    job.setPrintable(new PrintDialogExample(), pf);
    boolean ok = job.printDialog(aset);
    if (ok) {
        try {
            job.print(aset);
        } catch (PrinterException ex) {
            /* The job did not successfully complete */
        }
    }
    System.exit(0);
}

From source file:groovesquid.Main.java

public static void main(String[] args) {

    System.setSecurityManager(null);

    log.log(Level.INFO, "Groovesquid v{0} running on {1} {2} ({3}) in {4}",
            new Object[] { version, System.getProperty("java.vm.name"),
                    System.getProperty("java.runtime.version"), System.getProperty("java.vm.vendor"),
                    System.getProperty("java.home") });

    // show gui// w ww  .  ja v  a 2s.  c  om

    // apple os x
    System.setProperty("apple.laf.useScreenMenuBar", "true");
    System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Groovesquid");
    // antialising
    System.setProperty("awt.useSystemAAFontSettings", "lcd");
    System.setProperty("swing.aatext", "true");
    // flackering bg fix
    System.setProperty("sun.awt.noerasebackground", "true");
    System.setProperty("sun.java2d.noddraw", "true");
    Toolkit.getDefaultToolkit().setDynamicLayout(true);

    try {
        //UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception ex) {
        log.log(Level.SEVERE, null, ex);
    }

    // load languages
    languages = loadLanguages();

    // Load config
    config = loadConfig();

    // GUI
    try {
        gui = (GUI) config.getGuiClass().newInstance();
    } catch (InstantiationException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
    settings = new Settings();
    about = new About();

    // Update Checker
    new UpdateCheckThread().start();

    // init grooveshark (every 25min)
    new InitThread().start();

}

From source file:net.frontlinesms.DesktopLauncher.java

/**
 * Main class for launching the FrontlineSMS project.
 * @param args//from   ww w  .  ja va 2s  . c  o  m
 */
public static void main(String[] args) {
    FrontlineSMS frontline = null;
    try {
        AppProperties appProperties = AppProperties.getInstance();
        final String VERSION = BuildProperties.getInstance().getVersion();
        LOG.info("FrontlineSMS version [" + VERSION + "]");
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        String lastVersion = appProperties.getLastRunVersion();
        InputStream defaultResourceArchive = ResourceUtils.class.getResourceAsStream("/resources.zip");
        if (defaultResourceArchive == null) {
            LOG.fatal("Default resources archive could not be found!");
            throw new Exception("Default resources archive could not be found!");
        }

        ResourceUtils.unzip(defaultResourceArchive, new File(ResourceUtils.getConfigDirectoryPath()),
                !VERSION.equals(lastVersion));

        // This should always get the English bundle, as other languages are only included in
        // resources.zip rather than in the resources/languages directory
        LanguageBundle englishBundle = InternationalisationUtils.getDefaultLanguageBundle();
        Thinlet.DEFAULT_ENGLISH_BUNDLE = englishBundle.getProperties();

        // If the user has currently no User ID defined
        // We generate one
        if (appProperties.getUserId() == null) {
            appProperties.setUserId(generateUserId());
        }

        boolean showWizard = appProperties.isShowWizard();
        appProperties.setLastRunVersion(VERSION);
        appProperties.saveToDisk();

        frontline = initFrontline();
        if (showWizard) {
            new FirstTimeWizard(frontline);
        } else {
            // Auto-detect phones.
            new UiGeneratorController(frontline, true);
        }
    } catch (Throwable t) {
        if (frontline != null)
            frontline.destroy();

        // Rather than swallowing the error, we now display it to the user
        // so that they can give us some feedback :)
        ErrorUtils.showErrorDialog("Fatal error starting FrontlineSMS!",
                "A problem ocurred during FrontlineSMS startup.", t, true);
    }
}

From source file:jeplus.Main.java

/**
 * @param args the command line arguments
 *///from ww w . java  2s . c  om
public static void main(String[] args) {
    //        if (REDIRECT_ERR) {
    //            try {
    //                // Redirect err
    //                System.setErr(new PrintStream(new FileOutputStream("jeplus.err")));
    //            } catch (FileNotFoundException ex) {
    //                //Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    //                ex.printStackTrace();
    //            }
    //        }

    try {
        // Set cross-platform Java L&F (also called "Metal")
        //            UIManager.setLookAndFeel(
        //                UIManager.getCrossPlatformLookAndFeelClassName());
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        //            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
        //                if ("Nimbus".equals(info.getName())) {
        //                    UIManager.setLookAndFeel(info.getClassName());
        //                    break;
        //                }
        //            }
    } catch (UnsupportedLookAndFeelException e) {
        System.err.println("Unsupported Look-And-Feel Option. Reverting to the default UI.");
    } catch (ClassNotFoundException e) {
        System.err.println("Specified Look-And-Feel class cannot be found. Reverting to the default UI.");
    } catch (InstantiationException e) {
        System.err.println("Fialed to instantiate the specified Look-And-Feel. Reverting to the default UI.");
    } catch (IllegalAccessException e) {
        System.err.println("Cannot access the specified Look-And-Feel. Reverting to the default UI.");
    }

    // Set locale to UK
    Locale.setDefault(Locale.UK);
    // Set line end to DOS style
    System.setProperty("line.separator", "\r\n");
    // System.setProperty("file.separator", "/");  // seemed to have no effect

    // create the parser
    CommandLineParser parser = new GnuParser();
    Options options = new Main().getCommandLineOptions(null);
    CommandLine commandline = null;
    HelpFormatter formatter = new HelpFormatter();
    formatter.setWidth(80);
    try {
        // parse the command line arguments
        commandline = parser.parse(options, args);
        if (commandline.hasOption("help")) {
            // automatically generate the help statement
            formatter.printHelp("java -Xmx1000m -jar jEPlus.jar [OPTIONS]", options);
            System.exit(-1);
        }
        // Set log4j configuration
        if (commandline.hasOption("log")) {
            PropertyConfigurator.configure(commandline.getOptionValue("log"));
        } else {
            PropertyConfigurator.configure("log4j.cfg");
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        // automatically generate the help statement
        formatter.printHelp("java -Xmx1000m -jar jEPlus.jar [OPTIONS]", options);
        System.exit(-1);
    }

    // Call main fuction with commandline
    new Main().mainFunction(commandline);
}

From source file:misc.TablePrintDemo2.java

/**
 * Start the application./*from  w w w .ja  v  a  2s .c om*/
 */
public static void main(final String[] args) {
    /* Schedule for the GUI to be created and shown on the EDT */
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            /* Don't want bold fonts if we end up using metal */
            UIManager.put("swing.boldMetal", false);
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
            }
            new TablePrintDemo2().setVisible(true);
        }
    });
}

From source file:de.topobyte.livecg.LiveCG.java

public static void main(String[] args) {
    // @formatter:off
    Options options = new Options();
    OptionHelper.add(options, OPTION_CONFIG, true, false, "path", "config file");
    // @formatter:on

    CommandLineParser clp = new GnuParser();

    CommandLine line = null;/* ww  w.  j  a  v  a  2 s . co  m*/
    try {
        line = clp.parse(options, args);
    } catch (ParseException e) {
        System.err.println("Parsing command line failed: " + e.getMessage());
        new HelpFormatter().printHelp(HELP_MESSAGE, options);
        System.exit(1);
    }

    StringOption config = ArgumentHelper.getString(line, OPTION_CONFIG);
    if (config.hasValue()) {
        String configPath = config.getValue();
        LiveConfig.setPath(configPath);
    }

    Configuration configuration = PreferenceManager.getConfiguration();
    String lookAndFeel = configuration.getSelectedLookAndFeel();
    if (lookAndFeel == null) {
        lookAndFeel = UIManager.getSystemLookAndFeelClassName();
    }
    try {
        UIManager.setLookAndFeel(lookAndFeel);
    } catch (Exception e) {
        logger.error("error while setting look and feel '" + lookAndFeel + "': " + e.getClass().getSimpleName()
                + ", message: " + e.getMessage());
    }

    Content content = null;
    String filename = "res/presets/Startup.geom";

    String[] extra = line.getArgs();
    if (extra.length > 0) {
        filename = extra[0];
    }

    ContentReader reader = new ContentReader();
    InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(filename);
    try {
        content = reader.read(input);
    } catch (Exception e) {
        logger.info("unable to load startup geometry file", e);
        logger.info("Exception: " + e.getClass().getSimpleName());
        logger.info("Message: " + e.getMessage());
    }

    final LiveCG runner = new LiveCG();
    final Content c = content;

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            runner.setup(true, c);
        }
    });
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            runner.frame.requestFocus();
        }
    });
}

From source file:com.ibm.soatf.SOATestingFramework.java

/**
 * SOA Testing Framework main static method.
 *
 * @param args Main input parameters./*from  www. j  a v  a2  s . c  o  m*/
 */
public static void main(String[] args) {
    Options options = new Options();
    options.addOption(new Option("gui", "Display a GUI"));

    options.addOption(OptionBuilder.withArgName("environment").hasArg()
            .withDescription("Environment to run the tests on").create("env")); // has a value
    options.addOption(OptionBuilder.withArgName("project").hasArg()
            .withDescription("Project to run the tests on").create("p")); // has a value
    options.addOption(OptionBuilder.withArgName("interface").hasArg()
            .withDescription("Interface to run the tests on").create("i")); // has a value
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);
        validate(cmd);

        if (cmd.hasOption("gui")) {

            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
             */
            try {
                if (false) { //disabled the OS Look'n'Feel
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } else {
                    for (UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                        if ("Nimbus".equals(info.getName())) {
                            javax.swing.UIManager.setLookAndFeel(info.getClassName());
                            break;
                        }
                    }
                    UIManager.getLookAndFeelDefaults().put("nimbusOrange", (new Color(0, 128, 255)));
                }
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                    | javax.swing.UnsupportedLookAndFeelException ex) {
                logger.error("Cannot set look and feel", ex);
            }
            //</editor-fold>

            final SOATestingFrameworkGUI soatfgui = new SOATestingFrameworkGUI();
            java.awt.EventQueue.invokeLater(new Runnable() {

                @Override
                public void run() {
                    soatfgui.setVisible(true);
                }
            });
        } else {
            //<editor-fold defaultstate="collapsed" desc="Command line mode">
            try {
                // Initialization of configuration manager.
                ConfigurationManager.getInstance().init();

                String env = cmd.getOptionValue("env", null);
                String ifaceName;
                boolean inboundOnly = false;
                if (cmd.hasOption("p")) {
                    String projectName = cmd.getOptionValue("p");
                    MasterConfiguration masterConfig = ConfigurationManager.getInstance().getMasterConfig();
                    List<SOATestingFrameworkMasterConfiguration.Interfaces.Interface> interfaces = masterConfig
                            .getInterfaces();
                    all: for (Interface iface : interfaces) {
                        List<Project> projects = iface.getProjects().getProject();
                        for (Project project : projects) {
                            if (project.getName().equals(projectName)) {
                                inboundOnly = "INBOUND".equalsIgnoreCase(project.getDirection());
                                ifaceName = iface.getName();
                                break all;
                            }
                        }
                    }
                    throw new FrameworkExecutionException(
                            "No such project found in master configuration: " + projectName);
                } else {
                    ifaceName = cmd.getOptionValue("i");
                    inboundOnly = false;
                }
                DirectoryStructureManager.checkFrameworkDirectoryStructure(ifaceName);
                FlowExecutor flowExecutor = new FlowExecutor(inboundOnly, env, ifaceName);
                flowExecutor.execute();
            } catch (FrameworkConfigurationException ex) {
                logger.fatal("Configuration corrupted. See the exception stack trace for details.", ex);
            } catch (FrameworkException ex) {
                logger.fatal(ex);
            }
            //</editor-fold>
        }
    } catch (ParseException ex) {
        logger.fatal("Could not parse the command line arguments. Reason: " + ex);
        printUsage();
    } catch (Throwable ex) {
        logger.fatal("Unexpected error occured: ", ex);
        printUsage();
        System.exit(-1);
    }
}

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  www . j  av  a  2s  .  c om*/
        }
    }

    // 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());
        });
    });
}

From source file:fr.eurecom.hybris.demogui.HybrisDemoGui.java

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                new HybrisDemoGui();
            } catch (Exception e) {
                e.printStackTrace();//w  ww .  ja  va 2  s. c o m
            }
        }
    });
}