Java设置窗口居中

Java设置窗口居中

package ui;

import javax.swing.*;
import java.awt.*;

public class ScreenCut extends JFrame {
    public ScreenCut() throws HeadlessException {
        initFrame();
    }
    private void initFrame(){
        this.setTitle("aa");
        this.setLayout(null);
        //设置窗口大小
        this.setSize(new Dimension(800,600));
        int windowWidth = this.getWidth(); //获得窗口宽
        int windowHeight = this.getHeight();//获得窗口高
        Toolkit kit = Toolkit.getDefaultToolkit(); //定义工具包
        Dimension screenSize = kit.getScreenSize(); //获取屏幕的尺寸
        int screenWidth = screenSize.width; //获取屏幕的宽
        int screenHeight = screenSize.height; //获取屏幕的高
        //设置窗口居中
        this.setLocation(screenWidth/2-windowWidth/2, screenHeight/2-windowHeight/2);//设置窗口居中显示
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //设置窗口大小不可变
        this.setResizable(false);
        this.setVisible(true);
    }

    public static void main(String[] args) {
        new ScreenCut();
    }
}

执行结果

Java设置窗口居中_第1张图片

你可能感兴趣的:(java)