Java 怎么让组件(Component)显示在屏幕中央

2019年8月18日22:01:31 评论 22

1.简介

Java 怎么让组件(Component)显示在屏幕中央?——请看下文。

2.代码

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


import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;

public class Main {
    
    static public void center(final Component thisComponent) {
        final Dimension thisScreenSize = Toolkit.getDefaultToolkit()
                .getScreenSize();
        final Dimension thisComponentSize = thisComponent.getSize();
        if (thisComponentSize.height > thisScreenSize.height) {
            thisComponentSize.height = thisScreenSize.height;
        }
        if (thisComponentSize.width > thisScreenSize.width) {
            thisComponentSize.width = thisScreenSize.width;
        }
        thisComponent.setLocation(
                (thisScreenSize.width - thisComponentSize.width) / 2,
                (thisScreenSize.height - thisComponentSize.height) / 2);
    }
}

 

3.总结

示例代码演示了 Java 怎么让组件(Component)显示在屏幕中央,具体步骤参见示例代码。

发表评论

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