Java Swing Tutorial - Java Swing Look and Feel








Swing supports pluggable look and feel (L&F).

We can change the L&F for a Swing application using the setLookAndFeel(String lafClassName) static method of the UIManager class.

The lafClassName argument is the fully qualified name of the class providing the L&F.

The following code sets the L&F for Windows:

String windowsLAF=  "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
try  {
    UIManager.setLookAndFeel(windowsLAF);
}
catch (Exception e)  {
    e.printStackTrace();
}

If we change the L&F after the GUI has been shown, we will need to update the GUI using the updateComponentTreeUI(container) method of the SwingUtilities class.

UIManager.setLookAndFeel(windowsLAF);
SwingUtilities.updateComponentTreeUI(frame);
frame.pack();

The following two methods of the UIManager class return the class names for the default Java L&F and the system L&F:

String getCrossPlatformLookAndFeelClassName()
String getSystemLookAndFeelClassName()

To Set the system (or native) L&F

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

The following code lists all available L&F on your machine.

import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
//w w w .ja  v  a2s  .c o m
public class Main {
  public static void main(String[] args) {

    LookAndFeelInfo[] lafList = UIManager.getInstalledLookAndFeels();

    for (LookAndFeelInfo lafInfo : lafList) {
      String name = lafInfo.getName();
      String className = lafInfo.getClassName();
      System.out.println("Name: " + name + ", Class Name: " + className);
    }
  }
}

The code above generates the following result.