Search code examples
javaswingjava-7java-6java-5

Java version compatibility when working with different api in different version for same task


i wrote a applet for screen Capture for jre 1.7, jre 1.6 and jre 1.5. The applet has to use transparent background for it's window. But for translucency jre 1.7(graphicDevice window Translucency) and 1.6(awtutilities) uses different api and there is work around for jre 1.5. Now how to make my applet compatible for all the three version?

I guess i have to compile different classes with different compilers. But how use these separately compiled classes in a single application?


Solution

  • If there are different APIs present in different versions of java for the same functionality(as JWindow.setOpacity() in java 1.7 and AWTUtilities.setWindowOpacity() in java 1.6), then we can use dynamic loading of classes to use the APIs depending on the availability of class w.r.t java version. Here is the code that solved my case :

        try
        {
            Class<?> cls = Class.forName("javax.swing.JWindow");
            Method meth = cls.getMethod("setOpacity", float.class);
            meth.invoke(transparentWindow, 0.50f);
        }
        catch (Throwable e)
        {
            e.printStackTrace();
            try
            {
                Class<?> cls = Class.forName("com.sun.awt.AWTUtilities");
                Method meth = cls.getMethod("setWindowOpacity", Window.class,
                                            float.class);
                meth.invoke(null, transparentWindow, 0.50f);
            }
            catch (Throwable e1)
            {
                e1.printStackTrace();
            }
        }
    

    Hope it helps to beginners like once I was :)