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

2019年8月18日21:59:21 评论 22

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

 

3.总结

示例代码演示了 Java 怎么将指定的组件居中显示在屏幕上,具体步骤参见示例代码。

发表评论

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