Java 怎么返回cont中点p与cont的comp a后代之间的距离

2019年8月18日21:59:28 评论 23

1.简介

Java 怎么返回cont中点p与cont的comp a后代之间的距离?——请看下文。

2.代码

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


import java.awt.Component;
import java.awt.Container;
import java.awt.Point;
import java.awt.Rectangle;

public class Main {
    public static double getDistance(Point p, Rectangle bounds) {
        if (bounds.contains(p))
            return 0;
        else {
            final int x = getNearest(p.x, bounds.x, bounds.x + bounds.width);
            final int y = getNearest(p.y, bounds.y, bounds.y
                    + bounds.height);
            final int diffX = Math.abs(p.x - x);
            final int diffY = Math.abs(p.y - y);
            return Math.sqrt(diffX * diffX + diffY * diffY);
        }

    }

    
    public static double getDistance(Container cont, Point p,
            final Component comp, Rectangle bounds) {
        return getDistance(p, getBoundsInAncestor(cont, comp, bounds));
    }

    private static int getNearest(int p, int start, int end) {
        if (p < start)
            return start;
        else if (p > end)
            return end;
        else
            return p;
    }

    public static Rectangle getBoundsInAncestor(Container ancestor,
            final Component comp, Rectangle bounds) {
        bounds = comp.getBounds(bounds);
        Container parent = comp.getParent();
        while (parent != null && parent != ancestor) {
            bounds.translate(parent.getX(), parent.getY());
            parent = parent.getParent();
        }
        return bounds;
    }
}

 

3.总结

示例代码演示了 Java 怎么返回cont中点p与cont的comp a后代之间的距离,具体步骤参见示例代码。

发表评论

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