Java 怎么将点从上组件转换为另一组件

2019年8月18日21:59:44 评论 21

1.简介

Java 怎么将点从上组件转换为另一组件?——请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */



public class Main {
    public static java.awt.Point convertPoint(java.awt.Component src,
            int srcX, int srcY, java.awt.Component dst) {
        java.awt.Component srcRoot = javax.swing.SwingUtilities
                .getRoot(src);
        java.awt.Component dstRoot = javax.swing.SwingUtilities
                .getRoot(dst);
        
        if ((srcRoot != null) && (srcRoot == dstRoot)) {
            java.awt.Point srcPt = getLocation(src, srcRoot);
            java.awt.Point dstPt = getLocation(dst, dstRoot);
            java.awt.Point rv = srcPt;
            rv.x -= dstPt.x;
            rv.y -= dstPt.y;
            rv.x += srcX;
            rv.y += srcY;
            return rv;
        } else {
            return javax.swing.SwingUtilities.convertPoint(src, srcX, srcY,
                    dst);
        }
    }

    public static java.awt.Point convertPoint(java.awt.Component src,
            java.awt.Point srcPt, java.awt.Component dst) {
        return convertPoint(src, srcPt.x, srcPt.y, dst);
    }

    private static java.awt.Point getLocation(java.awt.Point rv,
            java.awt.Component c, java.awt.Component ancestor) {
        assert c != null;
        if (c == ancestor) {
            return rv;
        } else {
            rv.x += c.getX();
            rv.y += c.getY();
            return getLocation(rv, c.getParent(), ancestor);
        }
    }

    private static java.awt.Point getLocation(java.awt.Component c,
            java.awt.Component ancestor) {
        return getLocation(new java.awt.Point(), c, ancestor);
    }
}

 

3.总结

示例代码演示了 Java 怎么将点从上组件转换为另一组件,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: