Java圖形界面編程---------使窗體加載時處於正中間

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);
		
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章