Java 怎么将指定的组件居中显示在屏幕上

2019年8月18日21:59:21Java 怎么将指定的组件居中显示在屏幕上已关闭评论 142 640字阅读2分8秒

1.简介

Java 怎么将指定的组件居中显示在屏幕上?——请看下文。

2.示例代码

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


import java.awt.*;

public class Main {
    
    public static void center(Component component) {
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension screenSize = toolkit.getScreenSize();

        int x = (screenSize.width - component.getWidth()) / 2;
        int y = (screenSize.height - component.getHeight()) / 2;

        component.setLocation(x, y);
    }

    
    public static void center(Component parent, Component child) {
        Dimension parentSize = parent.getSize();
        Point parentLocation = parent.getLocation();

        int x = (parentSize.width - child.getWidth()) / 2;
        int y = (parentSize.height - child.getHeight()) / 2;

        child.setLocation(parentLocation.x + x, parentLocation.y + y);
    }
}

 
编程十万个怎么办