Give an example:
1. There is a 200*200 pixel window. If you want to place it in the middle of the 800*600 pixel screen, the screen position should be (800/2, 600/2) = (400, 300)
2. In order to set the position of the upper left corner of the window so that the center of the window matches the center of the screen, two small conditions must meet (1) Half or 100 pixels of the window must fall to the left of the center of the screen (2) Half or 100 pixels of the window must fall above the center of the screen, so the position of the upper left corner of the window must be positioned at (400-100, 300-100) = (300, 200)
As shown in the figure below:
However, during the actual program operation, the actual size and pixel clarity of the display screen of the program's running environment are different. We must be able to dynamically judge the size of the computer screen running Java programs so that the program can be centered no matter what computer it runs on. JAVA's AWT provides a Toolkit class to enable us to make a judgment!
Specific application
1. Call a static method getDefaultToolkit() on Toolkit class to obtain a handle on Toolkit object of the AWT for this platform.
2. Then call getScreenSize() method of Toolkit object, which returns a Dimension (Chinese meaning dimension) class object. The Demension object has exactly two public int attributes, namely width (in pixels), and heigth (in pixels)
3. "Tie" this method call together because we don't want to keep Toolkit object for a long time. We just want to use it temporarily to restore Dimension object of the screen
Code:
Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
Therefore, there is no need to assign a handle to the Toolkit object to the reference variable.
Program code:
import javax.swing.*;public class FrameTest {public static void main (String[] args) {JFrame theFrame = new JFrame("Whee!!!");theFrame.setSize(200, 200);dimensional frameSize=theFrame.getSize();Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();int centerX = screenSize.width/2;int centerY = screeSize.height/2; theFrame.setlocation(centerX-halfwidth,centerY-halfHeight); theFrame.setVisible(true);}}Summarize
The above is the entire content of this article. I hope it will be helpful to everyone's study and work. If you have any questions, please leave a message to communicate.