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();
}
}
执行结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190617235706304.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM5NDAwOTg0,size_16,color_FFFFFF,t_70)