Detecting what version of Swing is installed

One way to find out is to look at the UIDefaults key/value pairs to see what new keys have been introduced in what version.

Here’s an example, test it thouroughly. If anyone knows a better way, comment it here!

GetSwingVersion.java:

import java.lang.reflect.*;
import java.util.*;
 
public class GetSwingVersion
{
   public static void main(String []args) {
      boolean found = false;
 
      try {
         Class.forName("javax.swing.JButton");
 
         Class manager = Class.forName("javax.swing.UIManager");
         try {
            Method m = manager.getDeclaredMethod("getDefaults", new Class[] { });
            Object defaults = m.invoke(null, new Object[] { });
 
            Method qd = defaults.getClass().getMethod("getString", new Class[] { Object.class });
            Object str = qd.invoke(defaults, new Object[] { "FormattedTextFieldUI" });
            if (str != null) {
               System.out.println("Swing version 1.1.1 JDK1.4 found!");
            }
            else {
               Object str2 = qd.invoke(defaults, new Object[] { "RootPaneUI" });
               if (str2 != null) {
                  System.out.println("Swing version 1.1.1 JDK1.3 found!");
               }
               else {
                  System.out.println("Swing version 1.1.1 JDK1.2.2 found!");
               }
            }
         }
         catch(NoSuchMethodException e) {
         }
         catch(IllegalAccessException e) {
         }
         catch(InvocationTargetException e) {
         }
  
         found = true;
      }
      catch(NoClassDefFoundError e) {
      }
      catch(ClassNotFoundException e) {
      }
 
      if (!found) {  
         try {
            Class.forName("com.sun.java.swing.JButton");
            System.out.println("Swing v1.0.3 found!");
            found = true;
         } 
         catch(NoClassDefFoundError e) {
         }
         catch(ClassNotFoundException e) {
         }
      }   
 
      if (!found) {
         System.out.println("no version of Swing found!");
      }
 
      System.exit(1);
   }
}