Home > Java > javaTutorial > What are the methods for centering a Java form?

What are the methods for centering a Java form?

零下一度
Release: 2017-07-16 17:00:52
Original
1776 people have browsed it

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);//设置窗口居中显示
Copy after login

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);
Copy after login

03. The third method is the method provided after jdk1.4

 setLocationRelativeTo(owner);
Copy after login

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template