Phương thức setLocationRelativeTo(null)
Mặc định JFrame xuất hiện ở góc trên-trái (0,0). Để căn giữa màn hình, gọi setLocationRelativeTo(null) sau khi pack() hoặc setSize() và trước setVisible(true).
Cú pháp
public void setLocationRelativeTo(Component c)
Truyền null để căn giữa màn hình (GraphicsEnvironment). Truyền một Component khác để căn giữa so với component đó.
Ví dụ hoàn chỉnh
import javax.swing.*;
import java.awt.*;
public class CenteredFrameExample extends JFrame {
public CenteredFrameExample() {
setTitle("JFrame ở giữa màn hình");
add(new JLabel("JFrame được căn giữa màn hình", SwingConstants.CENTER), BorderLayout.CENTER);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); // Quan trọng: căn giữa
setVisible(true);
}
public static void main(String[] args) {
// Chạy trên EDT (Event Dispatch Thread)
SwingUtilities.invokeLater(CenteredFrameExample::new);
}
}
Kết quả
Cửa sổ JFrame xuất hiện chính giữa màn hình.

Best practice: Luôn khởi tạo Swing UI trên EDT bằng SwingUtilities.invokeLater().