Java 怎么对齐组件

2019年8月18日22:00:23 评论 21

1.简介

Java 怎么对齐组件?——请看下文。

2.代码

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


import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;

import java.awt.Toolkit;

public class Main {
    private static Dimension SCREEN_SIZE = Toolkit.getDefaultToolkit()
            .getScreenSize();

    static public void alignComponents(Component child, Component parent) {
        Point location = parent.getLocation();
        Dimension parentSize = parent.getSize();
        Dimension childSize = child.getSize();

        if ((location.x - childSize.width) > 0) {
            location.x -= childSize.width;
            child.setLocation(location);
        } else if ((location.x + parentSize.width + childSize.width) < SCREEN_SIZE.width) {
            location.x += parentSize.width;
            child.setLocation(location);
        } else
            centerComponent(child, location, parentSize);
    }

    static public void centerComponent(Component child,
            Point parentLocation, Dimension parentSize) {
        Dimension childSize = child.getSize();

        if (childSize.width > parentSize.width)
            childSize.width = parentSize.width;
        if (childSize.height > parentSize.height)
            childSize.height = parentSize.height;
        child.setLocation(parentLocation.x + parentSize.width / 2
                - childSize.width / 2, parentLocation.y + parentSize.height
                / 2 - childSize.height / 2);
    }
}

 

3.总结

示例代码演示了 Java 怎么对齐组件,具体步骤参见示例代码。

发表评论

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