Desktop application development using Java SWING or AWT, the main window may be provided with a position generally centrally of the main window, use the following method:
01, a first method
int windowWidth = frame.getWidth (); // get the window width int windowHeight = frame.getHeight (); // get a high window Toolkit kit = Toolkit.getDefaultToolkit (); // define Kit Dimension screenSize = kit.getScreenSize (); // Get size of the screen int screenWidth = screenSize.width; // Get the screen width int screenHeight = screenSize.height; // Get screen high frame.setLocation (screenWidth / 2-windowWidth / 2 , screenHeight / 2-windowHeight / 2 ); // set centered window 02, the second method Toolkit kit = Toolkit.getDefaultToolkit (); // define Kit Dimension screenSize = kit.getScreenSize (); // Get the screen size
int screenWidth = screenSize.width / 2; // Get the screen width
int screenHeight = screenSize.height / 2; // Get high screen
int height = this.getHeight ();
int width = this.getWidth ();
the setLocation ( screenWidth-width / 2, screenHeight- height / 2);
int screenWidth = screenSize.width / 2; // Get the screen width
int screenHeight = screenSize.height / 2; // Get high screen
int height = this.getHeight ();
int width = this.getWidth ();
the setLocation ( screenWidth-width / 2, screenHeight- height / 2);
03, the third method, a method is provided after jdk1.4
setLocationRelativeTo (owner); //
this is a set window relative to the position of another window (typically centered in the middle of the parent window), if the owner == null resident on the center of the screen window.
So the quickest way is to set up: jf.setLocationRelativeTo (null); // make the form center
04, the fourth method,
When a large plurality of display screens can be used together consisting of a simultaneous display window, can achieve the centering, the centering window to previous methods, a screen is limited to the current window center.
private void setFrameCenterToScreenCenter_2(){
Point pointSreenCenter = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
setLocation(pointSreenCenter.x-getSize().width/2, pointSreenCenter.y-getSize().height/2);
}
setLocation(pointSreenCenter.x-getSize().width/2, pointSreenCenter.y-getSize().height/2);
}