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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
		

本文出自 “11941149” 博客,请务必保留此出处http://11951149.blog.51cto.com/11941149/1851444

以上是关于Java图形界面编程---------使窗体加载时处于正中间的主要内容,如果未能解决你的问题,请参考以下文章

java 要输出格子图形该怎么编程 +---+---+ +---+---+

java怎么将查询到的数据库的内容显示到java图形界面上?

java怎么将查询到的数据库的内容显示到java图形界面上?

java 图形化界面笔记(1)

怎样用java编写图形界面的Application程序

java图形用户界面编程实例,经典好文