Java图形界面编程---------使窗体加载时处于正中间


很多时候我们在创建一个Java界面应用时,我们都想如果可以在运行程序的时候初始化窗体就处于屏幕


的正中间,那该多好!接下来我将介绍两种方法实现窗体居中。




一、方法一


        使用java.awt.Window中的setLocationRelativeTo(Component c);方法进行设置。


        setLocationRelativeTo(Component c);

        Sets the location of the window relative to the specified component according to the following scenarios.

        The target screen mentioned below is a screen to which the window should be placed after the setLocationRelativeTo method is called.

        If the component is null(如果为空), or the GraphicsConfiguration associated with this component is null, the window is placed in the center of the screen. The center point can be obtained with the GraphicsEnvironment.getCenterPoint method.

        If the component is not null, but it is not currently showing, the window is placed in the center of the target screen defined by theGraphicsConfiguration associated with this component.

        If the component is not null and is shown on the screen, then the window is located in such a way that the center of the window coincides with the center of the component.


代码如下:

        

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;

public class LoadPosition extends JFrame{

	private static final long serialVersionUID = 1L;
	
	public LoadPosition(){
		
		this.setTitle("Load_Position");
		
		this.setSize(700,500);
		
		this.setVisible(true);
		
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		//为当前窗口设置事件监听器,使用Window适配器
		this.addWindowListener(new WindowAdapter() {

			@Override
			public void windowOpened(WindowEvent e) {
			        //在此调用该方法
				setLocationRelativeTo(null);
			}
		});
	}
	public static void main(String[] args) {
		new LoadPosition();
	}
}



二、方法二


public Frame01(){
		
		super("Frame01");
		this.setResizable(false);
		//设置窗体的大小
		this.setSize(800, 500);
		//设置背景颜色
		this.getContentPane().setBackground(new Color(152,251,152));
		//Dimension封装了电脑屏幕的宽度和高度
		//获取屏幕宽度和高度,使窗口位于屏幕正中间
		Dimension width=Toolkit.getDefaultToolkit().getScreenSize();
		
		this.setLocation((int)(width.getWidth()-799)/2,(int)(width.getHeight()-500)/2);