Example usage for javax.swing UIManager setLookAndFeel

List of usage examples for javax.swing UIManager setLookAndFeel

Introduction

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

Prototype

@SuppressWarnings("deprecation")
public static void setLookAndFeel(String className) throws ClassNotFoundException, InstantiationException,
        IllegalAccessException, UnsupportedLookAndFeelException 

Source Link

Document

Loads the LookAndFeel specified by the given class name, using the current thread's context class loader, and passes it to setLookAndFeel(LookAndFeel) .

Usage

From source file:ListProperties.java

public static void main(String args[]) {
    final JFrame frame = new JFrame("List Properties");

    final CustomTableModel model = new CustomTableModel();
    model.uiDefaultsUpdate(UIManager.getDefaults());
    TableSorter sorter = new TableSorter(model);

    JTable table = new JTable(sorter);
    TableHeaderSorter.install(sorter, table);

    table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

    UIManager.LookAndFeelInfo looks[] = UIManager.getInstalledLookAndFeels();

    ActionListener actionListener = new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            final String lafClassName = actionEvent.getActionCommand();
            Runnable runnable = new Runnable() {
                public void run() {
                    try {
                        UIManager.setLookAndFeel(lafClassName);
                        SwingUtilities.updateComponentTreeUI(frame);
                        // Added
                        model.uiDefaultsUpdate(UIManager.getDefaults());
                    } catch (Exception exception) {
                        JOptionPane.showMessageDialog(frame, "Can't change look and feel", "Invalid PLAF",
                                JOptionPane.ERROR_MESSAGE);
                    }//from w  ww  .  ja  v a2s  . c  o  m
                }
            };
            SwingUtilities.invokeLater(runnable);
        }
    };

    JToolBar toolbar = new JToolBar();
    for (int i = 0, n = looks.length; i < n; i++) {
        JButton button = new JButton(looks[i].getName());
        button.setActionCommand(looks[i].getClassName());
        button.addActionListener(actionListener);
        toolbar.add(button);
    }

    Container content = frame.getContentPane();
    content.add(toolbar, BorderLayout.NORTH);
    JScrollPane scrollPane = new JScrollPane(table);
    content.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(400, 400);
    frame.setVisible(true);
}

From source file:misc.TablePrintDemo2.java

/**
 * Start the application./*from ww  w.  ja  v a2 s .  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:StylesExample8.java

public static void main(String[] args) {
    try {/*from w  w  w .ja  v a  2 s  .c  om*/
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {
    }

    JFrame f = new JFrame("Styles Example 8");

    // Create the StyleContext, the document and the pane
    final StyleContext sc = new StyleContext();
    final DefaultStyledDocument doc = new DefaultStyledDocument(sc);
    final JTextPane pane = new JTextPane(doc);

    // Build the styles
    createDocumentStyles(sc);

    try {
        // Add the text and apply the styles
        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
                // Add the text
                addText(pane, sc, sc.getStyle(mainStyleName), content);
            }
        });
    } catch (Exception e) {
        System.out.println("Exception when constructing document: " + e);
        System.exit(1);
    }

    f.getContentPane().add(new JScrollPane(pane));
    f.setSize(500, 300);
    f.setVisible(true);
}

From source file:TextPaneElements.java

public static void main(String[] args) {
    try {/*  w w w  . java  2s  . c o  m*/
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {
    }

    JFrame f = new JFrame("Text Pane Elements");

    // Create the StyleContext, the document and the pane
    final StyleContext sc = new StyleContext();
    final DefaultStyledDocument doc = new DefaultStyledDocument(sc);
    final JTextPane pane = new JTextPane(doc);

    // Build the styles
    createDocumentStyles(sc);

    try {
        // Add the text and apply the styles
        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
                // Add the text
                addText(pane, sc, sc.getStyle(mainStyleName), content);

                // Dump the element structure
                ((AbstractDocument) pane.getDocument()).dump(System.out);
            }
        });
    } catch (Exception e) {
        System.out.println("Exception when constructing document: " + e);
        System.exit(1);
    }

    f.getContentPane().add(new JScrollPane(pane));
    f.setSize(500, 300);
    f.setVisible(true);
}

From source file:layout.BorderLayoutDemo.java

public static void main(String[] args) {
    /* Use an appropriate Look and Feel */
    try {/*  w  w  w  . java  2s  . co m*/
        //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
    } catch (UnsupportedLookAndFeelException ex) {
        ex.printStackTrace();
    } catch (IllegalAccessException ex) {
        ex.printStackTrace();
    } catch (InstantiationException ex) {
        ex.printStackTrace();
    } catch (ClassNotFoundException ex) {
        ex.printStackTrace();
    }
    /* Turn off metal's use bold fonts */
    UIManager.put("swing.boldMetal", Boolean.FALSE);

    //Schedule a job for the event dispatch thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}

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;//from   w  w w. ja  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 w  w w  .  ja  va  2 s . com
 */
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:es.tunelator.Start.java

/**
 * Bootstraps the application, creates and shows the user interface
 * @param args//  w  w w. j  ava 2s .  c o  m
 */
public static void main(String[] args) {
    MainFrame frame = null;
    try {

        //            LogFactory.getFactory().setAttribute(LogFactoryImpl.LOG_PROPERTY,
        //                    Log4JLogger.class.getName());
        //            PropertyConfigurator.configure(Start.class.getClassLoader().
        //                    getResource("log4j.properties"));
        // Set log level as configured at the application parameters            
        Logger.setLogThreshold(AppParameters.getParams().getProperty("log.threshold", AppParameters.LOG_ERROR));
        //        If the language of the default locale is not supported revert to english
        if (!isLocaleSupported()) {
            Locale.setDefault(new Locale("en", "", ""));
        } else {
            Locale.setDefault(new Locale(Locale.getDefault().getLanguage(), "", ""));
        }
        // Log application startup          
        Logger.logInfo(Start.class, Resourcer.getString(null, "log.info.startup"));
        // To set up the Look and Feel
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows." + "WindowsLookAndFeel");
        frame = new MainFrame();
        frame.setVisible(true);
        frame.correctTabStatus();
        // To change the Look and Feel. To be included as an option some day...
        //          UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk."+
        //          "GTKLookAndFeel");
        //          SwingUtilities.updateComponentTreeUI(frame);
        //          frame.pack();
    } catch (Exception e) {
        Logger.logFatal(Start.class, e);
        if (frame != null) {
            frame.showErrorMessage(Resourcer.getString(null, "error.internal"));
            frame.dispose();
        } else {
            try {
                JOptionPane.showMessageDialog(null, Resourcer.getString(Start.class, "error.internal"),
                        Resourcer.getString(Start.class, "error.title"), JOptionPane.ERROR_MESSAGE);
            } catch (Exception e2) {
                String message = "";
                // This is the last resort to give a localized message
                // As I'm spanish :-), we give a spanish message if it's
                // the default language, and an english one otherwise.
                if (Locale.getDefault().getLanguage().equals(new Locale("es", "", "").getLanguage())) {
                    message = message_es;
                } else {
                    message = message_en;
                }
                JOptionPane.showMessageDialog(null, message, title, JOptionPane.ERROR_MESSAGE);
            }
        }
        System.exit(1);
    } catch (InternalError e) {
        Logger.logFatal(Start.class, e);
        if (frame != null) {
            frame.showErrorMessage(Resourcer.getString(null, "error.internal"));
            frame.dispose();
        } else {
            try {
                JOptionPane.showMessageDialog(null, Resourcer.getString(Start.class, "error.internal"),
                        Resourcer.getString(Start.class, "error.title"), JOptionPane.ERROR_MESSAGE);
            } catch (Exception e2) {
                String message = "";
                // This is the last resort to give a localized message
                // As I'm spanish :-), we give a spanish message if it's
                // the default language, and an english one otherwise.
                if (Locale.getDefault().getLanguage().equals(new Locale("es", "", "").getLanguage())) {
                    message = message_es;
                } else {
                    message = message_en;
                }
                JOptionPane.showMessageDialog(null, message, title, JOptionPane.ERROR_MESSAGE);
            }
        }
        System.exit(1);
    }
}

From source file:layout.CardLayoutDemo.java

public static void main(String[] args) {
    /* Use an appropriate Look and Feel */
    try {//from  w  w w .  j a  v a2 s. c  om
        //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
    } catch (UnsupportedLookAndFeelException ex) {
        ex.printStackTrace();
    } catch (IllegalAccessException ex) {
        ex.printStackTrace();
    } catch (InstantiationException ex) {
        ex.printStackTrace();
    } catch (ClassNotFoundException ex) {
        ex.printStackTrace();
    }
    /* Turn off metal's use of bold fonts */
    UIManager.put("swing.boldMetal", Boolean.FALSE);

    //Schedule a job for the event dispatch thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}

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;/*  w w  w .j  a v  a 2s.  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());
        });
    });
}