Saturday , July 27 2024

How to center a JFrame on screen in Java

Có một cách đơn giản để thiết lập vị trí trung tâm trên màn hình cho jframe như sau:

Sử dụng 2 gói java.awt.Dimensionjava.awt.Toolkit

1
2
import java.awt.Dimension;
import java.awt.Toolkit;

Viết một hàm để thiết lập vị trí trung tâm cho jframe:

1
2
3
4
5
6
7
8
9
10
11
12
private void centerLocation(){
    // get screen size
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    // get screen width, height
    int w = this.getSize().width;
    int h = this.getSize().height;
    // position x, y
    int x = (d.width - w)/2;
    int y = (d.height - h)/2;
    // set location for frame by position x, y
    this.setLocation(x, y);
}

Ở hàm khởi tạo của jfrane các bạn chỉ gọi hàm centerLocation() là xong. Ví dụ như sau:

1
2
3
4
public Example1() {
    initComponents();
    centerLocation();
}

Bây giờ thì chạy chương trình để xem kết quả thôi 🙂

Chúc các bạn thành công!

Download source: CenterJFrameOnScreen

About Ngo Thang IT

Một bình luận

  1. I just want to mention I’m very new to blogs and honestly loved your blog. Almost certainly I’m likely to bookmark your blog post . You surely come with good stories. Thanks a lot for sharing with us your webpage.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Đăng Ký Nhận Tin Qua Email

Nhận thông tin bổ ích về WordPress, Hosting, Thủ thuật website, Download miễn phí....và các phần quà hấp dẫn qua email.

* là bắt buộc