swing中怎么让窗口居中显示

swing中怎么让窗口居中显示

 

方法一:

  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. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值