Home >Java >javaTutorial >What are the methods for centering a Java form?
Java uses AWT or SWING to develop desktop programs. You can set the position of the main window so that the main window is centered. Generally, the following methods are used:
01. The first method
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. The second method
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. The third method is the method provided after jdk1.4
setLocationRelativeTo(owner);
This method is to set the position of one window relative to another window ( Generally centered in the middle of the parent window), if owner==null, the window will be centered on the screen.
4.
//setSize(300, 200); pack();// 得到显示器屏幕的宽、高int width = Toolkit.getDefaultToolkit().getScreenSize().width;int height = Toolkit.getDefaultToolkit().getScreenSize().height;// 得到窗体的宽、高int windowsWidth = this.getWidth();int windowsHeight = this.getHeight();//System.out.println(windowsWidth+","+windowsHeight);this.setBounds((width - windowsWidth) / 2,(height - windowsHeight) / 2, windowsWidth, windowsHeight);
The above is the detailed content of What are the methods for centering a Java form?. For more information, please follow other related articles on the PHP Chinese website!