Java 怎么对齐组件

2019年8月18日22:00:23Java 怎么对齐组件已关闭评论 170 1088字阅读3分37秒

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

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