您的位置:首页 > 其它

SWT编写界面窗口时让窗口处于屏幕中间

2011-04-08 00:36 811 查看
一、使用SWT本身

Java代码

 




import org.eclipse.swt.graphics.Rectangle;   

import org.eclipse.swt.widgets.Display;   

import org.eclipse.swt.widgets.Shell;   

  

public class LayoutUtil ...{   

  

    public static void centerShell(Display display,Shell shell)...{   

        Rectangle displayBounds = display.getPrimaryMonitor().getBounds();   

        Rectangle shellBounds = shell.getBounds();   

        int x = displayBounds.x + (displayBounds.width - shellBounds.width)>>1;   

        int y = displayBounds.y + (displayBounds.height - shellBounds.height)>>1;   

        shell.setLocation(x, y);   

    }   

}  

import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class LayoutUtil ...{

public static void centerShell(Display display,Shell shell)...{
Rectangle displayBounds = display.getPrimaryMonitor().getBounds();
Rectangle shellBounds = shell.getBounds();
int x = displayBounds.x + (displayBounds.width - shellBounds.width)>>1;
int y = displayBounds.y + (displayBounds.height - shellBounds.height)>>1;
shell.setLocation(x, y);
}
}


直接调用LayoutUtil.centerShell(Display display,Shell shell)即可使SWT窗口处于屏幕中央,其中,shell 要显示的Shell对象。
二、借助AWT包里面获取屏幕大小的方法

Java代码

 




import java.awt.Toolkit;   

/** *//**  

* 在屏幕中间显示Shell  

* @param shell 要显示的Shell对象  

*/  

private void centerShell(Shell shell)   

{   

         //得到屏幕的宽度和高度   

         int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;   

         int screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width;   

         //得到Shell窗口的宽度和高度   

         int shellHeight = shell.getBounds().height;   

         int shellWidth = shell.getBounds().width;   

         //如果窗口大小超过屏幕大小,让窗口与屏幕等大   

         if(shellHeight > screenHeight)   

                   shellHeight = screenHeight;   

         if(shellWidth > screenWidth)   

                  shellWidth = screenWidth;   

        //让窗口在屏幕中间显示   

        shell.setLocation(( (screenWidth - shellWidth) / 2),((screenHeight - shellHeight) / 2) );   

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: