Trong ví dụ đầu tiên, chúng ta tìm hiểu cách tạo 1 windows (cửa sổ) cơ bản bằng thư viện SWT
File SWTApp.java
package vncoding; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; public class SWTApp { public SWTApp(Display display) { Shell shell = new Shell(display); shell.setText("Java SWT Basic"); shell.setSize(250, 200); center(shell); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } } public void center(Shell shell) { Rectangle bds = shell.getDisplay().getBounds(); Point p = shell.getSize(); int nLeft = (bds.width - p.x) / 2; int nTop = (bds.height - p.y) / 2; shell.setBounds(nLeft, nTop, p.x, p.y); } public static void main(String[] args) { Display display = new Display(); new SWTApp(display); display.dispose(); } }
Giải thích:
Trong đoạn code này tạo 1 cửa sổ kích thước 250×200, xuất hiện tại vị trí trung tâm. Trong mỗi ứng dụng SWT, có 2 class quan trọng. Đó là Display vàShell.
– Lớp Display chính là cầu nối giữa SWT và tầng dưới HĐH (hệ điều hành). Nó thực hiện vòng lặp bắt sự kiện (event loop) và cung cấp thông tin về HĐH.
– Lớp Shell mô tả 1 cửa sổ. Shell lấy Display làm parent, thì Shell đó gọi là Shell thứ nhất (top level shells). Các Shell khác được gọi là shell thứ cấp (secondary shell).
Shell shell = new Shell(display);
Cửa sổ cha được tạo
shell.setText("Java SWT Basic");
Set title cho cửa sổ cha.
shell.setSize(250, 200);
Set kích thước cho cửa sổ cha
shell.open();
Lệnh này để show cửa sổ lên màn hình
while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } }
Vòng lặp vô hạn bắt sự kiện (event loop)
Rectangle bds = shell.getDisplay().getBounds();
Lệnh này lấy độ phân giải của màn hình. Nếu làm việc với nhiều màn hình thì chúng ta nên sử dụng hàm getMonitor() thay cho hàm getDisplay().
int nLeft = (bds.width - p.x) / 2; int nTop = (bds.height - p.y) / 2;
Tính toán tọa độ góc trái, trên để hiển thị cửa sổ
shell.setBounds(nLeft, nTop, p.x, p.y);
Set đường bao cho Shell
Display display = new Display();
Display được tạo.
new SWTApp(display);
Tạo 1 đối tượng SWTApp.
display.dispose();
Khi close/exit cửa sổ, chúng ta nên trả về tài nguyên cho HĐH.
Kết quả:
Leave a Reply
You must be logged in to post a comment.