An example is provided:
1, there is a 200*200 pixel window, want to put it in the middle of 800*600 pixel screen, the location of the screen should be (800/2,600/2) = (400,300)
2. In order to set the position of the upper left corner of the window, to match the center of the window to the screen center, you must meet half or 100 pixels of the 2 small condition (1) window must fall to the left of the center of the screen (2) The half or 100 pixels of the window must fall above the center of the screen, Therefore, the position of the upper-left corner of the window must be located at (400-100,300-100) = (300,200)
As shown in the following illustration:
But in the process of running the actual program, the operating environment of the program shows that the actual size and pixel sharpness of the screen are not the same, we must be able to dynamically determine the size of the computer screen that runs the Java program so that the program can be centered on whatever computer it is running on, and the Java AWT provides a Toolkit
class, To make us judge!
Specific application
1. In Toolkit
class, a static method is used to get a handle on the getDefaultToolkit()
AWT object for this platform Toolkit
.
2, and then call the Toolkit
object's getScreenSize()
method, which returns a Dimension
(Chinese-Dimension) class object. Demension
object has exactly two public int
properties, that is, width
in pixels, and heigth
(in pixels)
3. Call this method "tie" together because we don't want to hold the object for a long time Toolkit
. We just want to use it temporarily to restore the objects on the screen. Dimension
Code:
Dimension Screensize=toolkit.getdefaulttoolkit (). Getscreensize ();
Therefore, you do not have to assign a Toolkit object's handle to a reference variable.
Program code:
Import javax.swing.*;
public class Frametest {public
static void Main (string[] args) {
JFrame theframe = new JFrame ("Whee!!!");
Theframe.setsize (in);
Dimension 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 for everyone's study and work can help. If you have questions, you can exchange messages.