如何使frame能居中显示

 如何使frame能居中显示

有两种方式:
1. frame.setLocation()
setLocation
      public void setLocation(int x,
                           int y)
将组件移到新位置。通过此组件父级坐标空间中的 x 和 y 参数来指定新位置的左上角。
参数:
x - 父级坐标空间中新位置左上角的 x 坐标
y - 父级坐标空间中新位置左上角的 y 坐标
        因此,要使得窗口能够居中显示,代码如下:
[java] view plaincopyprint?
int windowWidth = frame.getWidth();                     //获得窗口宽  
 int windowHeight = frame.getHeight();                   //获得窗口高  
 Toolkit kit = Toolkit.getDefaultToolkit();              //定义工具包  
 Dimension screenSize = kit.getScreenSize();             //获取屏幕的尺寸  
 int screenWidth = screenSize.width;                     //获取屏幕的宽  
 int screenHeight = screenSize.height;                   //获取屏幕的高  
 frame.setLocation(screenWidth/2-windowWidth/2, screenHeight/2-windowHeight/2);//设置窗口居中显示  
2. setLocationRelativeTo()
setLocationRelativeTo
      public void setLocationRelativeTo(Component c)
设置窗口相对于指定组件的位置。
如果组件当前未显示,或者 c 为 null,则此窗口将置于屏幕的中央。中点可以使用 GraphicsEnvironment.getCenterPoint 确定。
如果该组件的底部在屏幕外,则将该窗口放置在 Component 最接近窗口中心的一侧。因此,如果 Component 在屏幕的右部,则Window 将被放置在左部,反之亦然。
参数:
c - 确定窗口位置涉及的组件
从以下版本开始:
1.4
              这种方法使用简单,代码如下:

frame.setLocationRelativeTo(null);    


 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值