Java_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);   
     }   
  
}  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章