如何使frame能居中显示

有两种方式:

1. frame.setLocation()

setLocation

      public void setLocation(int x,
                           int y)
将组件移到新位置。通过此组件父级坐标空间中的 xy 参数来指定新位置的左上角。

参数:
x - 父级坐标空间中新位置左上角的 x 坐标
y - 父级坐标空间中新位置左上角的 y 坐标

        因此,要使得窗口能够居中显示,代码如下:

       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)
设置窗口相对于指定组件的位置。

如果组件当前未显示,或者 cnull,则此窗口将置于屏幕的中央。中点可以使用 GraphicsEnvironment.getCenterPoint 确定。

如果该组件的底部在屏幕外,则将该窗口放置在 Component 最接近窗口中心的一侧。因此,如果 Component 在屏幕的右部,则Window 将被放置在左部,反之亦然。

参数:
c - 确定窗口位置涉及的组件
从以下版本开始:
1.4

              这种方法使用简单,代码如下:

frame.setLocationRelativeTo(null);  


 


 

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2011-11-22 14:36  wangicter的博客  阅读(695)  评论(0)    收藏  举报