swing窗口居中

来源:互联网 发布:mysql分组取最大值 编辑:程序博客网 时间:2024/06/10 09:41

方法一:

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

方法二:

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

方法三:

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

  1. import java.awt.GraphicsEnvironment;   
  2. import java.awt.Point;   
  3. import javax.swing.JFrame;   
  4.   
  5.   
  6. @SuppressWarnings("serial")   
  7. public class MyFrame extends JFrame {   
  8.   
  9.     private final int INIT_W = 600;  //窗体初始宽度   
  10.     private final int INIT_H = 460;  //窗体初始高度   
  11.   
  12.     public MyFrame() {   
  13.         super("Center Frame Test");   
  14.          Point p = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();   
  15.          setBounds(p.x - INIT_W / 2, p.y - INIT_H / 2, INIT_W, INIT_H);   
  16.          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   
  17.      }   
  18.   
  19.     public static void main(String[] args) {   
  20.         new MyFrame().setVisible(true);   
  21.      }   
  22.   
  23. }  
原创粉丝点击