Java 怎么获取离容器中某一点最近的组件(Component)

2019年8月18日22:01:56 评论 23

1.简介

Java 怎么获取离容器中某一点最近的组件(Component)?——请看下文。

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 final Component getNearestChild(final Container cont,
            final Point p) {
        Component res = null;
        double distance = Integer.MAX_VALUE;
        final Rectangle rv = new Rectangle();
        for (final Component comp : cont.getComponents()) {
            final double d = getDistance(p, comp.getBounds(rv));
            if (d < distance) {
                distance = d;
                res = comp;
            }
        }

        return res;
    }

    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 怎么获取离容器中某一点最近的组件(Component),具体步骤参见示例代码。

发表评论

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