How to set jframe look and feel

Yayatcm picture Yayatcm · Mar 2, 2012 · Viewed 49.3k times · Source

I am kind of confused on where to put this :

try {
    UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
    UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception e){

}

I did not extend the JFrame class but used JFrame f = new JFrame(); Thanks :D

Answer

kleopatra picture kleopatra · Mar 13, 2012

Note: this is not an answer to the question (which was where to set the LAF). Instead, it's answering the question how-to set an LAF in a manner that's independent on its package name. Simplifies life in case the class is moved, as f.i. Nimbus from com.sun* to javax.swing.

The basic approach is to query the UIManager for its installed LAFs, loop through them until a match is found and set that. Here'r such methods as implemented in SwingX:

/**
 * Returns the class name of the installed LookAndFeel with a name
 * containing the name snippet or null if none found.
 * 
 * @param nameSnippet a snippet contained in the Laf's name
 * @return the class name if installed, or null
 */
public static String getLookAndFeelClassName(String nameSnippet) {
    LookAndFeelInfo[] plafs = UIManager.getInstalledLookAndFeels();
    for (LookAndFeelInfo info : plafs) {
        if (info.getName().contains(nameSnippet)) {
            return info.getClassName();
        }
    }
    return null;
}

Usage (here without exception handling)

String className = getLookAndFeelClassName("Nimbus");
UIManager.setLookAndFeel(className);