Returns whether we can use the secured and 1.5 MouseInfo class - Java Swing

Java examples for Swing:Mouse Event

Description

Returns whether we can use the secured and 1.5 MouseInfo class

Demo Code

/*/*from  ww w.j  a  va 2  s .c  o  m*/
    VLDocking Framework 3.0
    Copyright Lilian Chamontin, 2004-2013
            
    www.vldocking.com
    vldocking@googlegroups.com
------------------------------------------------------------------------
This software is distributed under the LGPL license

The fact that you are presently reading this and using this class means that you have had
knowledge of the LGPL license and that you accept its terms.

You can read the complete license here :

    http://www.gnu.org/licenses/lgpl.html

 */
//package com.java2s;
import java.awt.*;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {
    /** Returns whether we can use the secured and 1.5 MouseInfo class */
    public static boolean canUseMouseInfo() {
        if (System.getProperty("java.version").compareTo("1.5") >= 0) {
            return getMouseLocation() != null;
        } else {
            return false; // not present in pre 1.5 versions
        }
    }

    /** Returns the mouse location on screen or null if ran in an untrusted environement/ java 1.4  */
    public static Point getMouseLocation() {
        try {
            //Point mouseLocation = MouseInfo.getPointerInfo().getLocation();
            // this class in not compatible with 1.4
            // so instead we use reflection for allowing 1.4 compilation
            Class<?> mouseInfoClass = Class.forName("java.awt.MouseInfo");
            @SuppressWarnings("rawtypes")
            final Class[] noArgs = new Class[0];
            Method m = mouseInfoClass.getMethod("getPointerInfo", noArgs);
            Object pointerInfo = m.invoke(null, (Object[]) null);
            Class<?> pointerInfoClass = Class
                    .forName("java.awt.PointerInfo");
            Method getLocationMethod = pointerInfoClass.getMethod(
                    "getLocation", noArgs);
            Point mouseLocation = (Point) getLocationMethod.invoke(
                    pointerInfo, (Object[]) null);
            return mouseLocation;
        } catch (ClassNotFoundException ignore) {
        } catch (NoSuchMethodException ignore) {
        } catch (IllegalAccessException e) {
        } catch (InvocationTargetException ignore) {
        }
        return null;
    }
}

Related Tutorials