java让窗体处于屏幕中间_Java图形界面编程---------使窗体加载时处于正中间

本文介绍了两种方法使Java界面应用在启动时居中显示:1) 使用`setLocationRelativeTo(null)`将窗体置于屏幕中心;2) 通过获取屏幕尺寸并计算坐标,设置窗体的位置来达到居中效果。
摘要由CSDN通过智能技术生成

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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值