JAVA桌面开发使窗体屏幕居中

Java开发桌面程序用AWT或SWING,可以用设置主窗口位置,使主窗口居中一般使用下面的方法:
01、第一种方法
       
     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);//设置窗口居中显示
  

02、第二种方法

     Toolkit kit = Toolkit.getDefaultToolkit();    // 定义工具包
     Dimension screenSize = kit.getScreenSize();   // 获取屏幕的尺寸
     int screenWidth = screenSize.width/2;         // 获取屏幕的宽
     int screenHeight = screenSize.height/2;       // 获取屏幕的高
     int height = this.getHeight();
     int width = this.getWidth();
     setLocation(screenWidth-width/2, screenHeight-height/2);

03、第三种方法,是jdk1.4之后提供的方法
     setLocationRelativeTo(owner);
    这种方法是设定一个窗口的相对于另外一个窗口的位置(一般是居中于父窗口的中间),如果owner==null则窗口就居于屏幕的中央。


04、第四种方法,可用于多个显示屏合起来组成的大型屏幕同时显示一个窗口时,也能实现居中功能,向之前的窗口居中方法,仅限于当前窗口一个屏幕居中。
private void setFrameCenterToScreenCenter_2(){
Point pointSreenCenter = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
setLocation(pointSreenCenter.x-getSize().width/2, pointSreenCenter.y-getSize().height/2);
}

你可能感兴趣的:(java,swing)