java中Frame Jpanel等中间显示

2022-11-12,,,

几种是窗口中间显示的方法:

1.Frame

 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.Window,Frame

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); //设置对象居中显示

3.jdk1.4之后提供了一直更便捷的方法

object.setLocationRelativeTo(null);

属于Window类的方法,任何继承它子类的具有这个方法。Frame,Panel....

其中的参数是objcet在其内居中显示的对象,上面的值是null,就是默认在屏幕中居中显示。

比如

jpanel.setLocationRelationTo(jFrame);

就是jpanel相对于jFrame居中显示。

java中Frame Jpanel等中间显示的相关教程结束。

《java中Frame Jpanel等中间显示.doc》

下载本文的Word格式文档,以方便收藏与打印。