Swing中怎么让窗口居中显示

方法一:

int windowWidth = frame.getWidth(); // 获得窗口宽   
int windowHeight = frame.getHeight(); // 获得窗口高   
Toolkit kit = Toolkit.getDefaultToolkit(); // 定义工具包   
Dimension screenSize = kit.getScreenSize(); // 获取屏幕的尺寸   
int screenWidth = screenSize.width; // 获取屏幕的宽   
int screenHeight = screenSize.height; // 获取屏幕的高   
frame.setLocation(screenWidth / 2 - windowWidth / 2, screenHeight / 2 - windowHeight / 2);// 设置窗口居中显示

方法二:

this.setLocationRelativeTo(null);//窗口在屏幕中间显示

方法三:

窗体都是相对于桌面(屏幕区域减去任务栏区域)而不是屏幕居中。
另外在 setLocationRelativeTo 内部也是通过调用 getCenterPoint 获得桌面中心点坐标的,所以上面第一种方式效率能稍稍高点。

import java.awt.GraphicsEnvironment;   
import java.awt.Point;   
import javax.swing.JFrame;   
  
  
@SuppressWarnings("serial")   
public class MyFrame extends JFrame {   
  
    private final int INIT_W = 600;  //窗体初始宽度   
    private final int INIT_H = 460;  //窗体初始高度   
  
    public MyFrame() {   
        super("Center Frame Test");   
         Point p = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();   
         setBounds(p.x - INIT_W / 2, p.y - INIT_H / 2, INIT_W, INIT_H);   
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   
     }   
  
    public static void main(String[] args) {   
        new MyFrame().setVisible(true);   
     }   
  
}  
发布了79 篇原创文章 · 获赞 55 · 访问量 32万+

猜你喜欢

转载自blog.csdn.net/qq_33833327/article/details/84234704