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

2019年8月18日21:59:28Java 怎么返回cont中点p与cont的comp a后代之间的距离已关闭评论 188 1044字阅读3分28秒

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;
    }
}

 
继续阅读
编程十万个怎么办