Java SWT – Button

Bài viết này sẽ hướng dẫn các bạn tạo 1 cửa sổ gồm 1 button. Khi ấn button, ứng dụng sẽ được close.

package vncoding;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class SWTApp {
    private Shell shell;
    public SWTApp(Display display) {
        shell = new Shell(display);
        shell.setText("Button");
        initUI();
        shell.setSize(250, 200);
        shell.setLocation(300, 300);
        shell.open();
        
        while (!shell.isDisposed()) {
          if (!display.readAndDispatch()) {
        	  display.sleep();
          }
        }
    }

    public void initUI() {
        Button quit = new Button(shell, SWT.PUSH);
        quit.setText("Quit");
        quit.setBounds(50, 50, 80, 30);
        
        quit.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                shell.getDisplay().dispose();
                System.exit(0);
            }
        });
    }

    public static void main(String[] args) {
        Display display = new Display();
        new SWTApp(display);
        display.dispose();
    }
}

Giải thích:
Chúng ta ta tạo hàm initUI() kiểu UI (User Interface).

Button quit = new Button(shell, SWT.PUSH);

Trong hàm initUI(), chúng ta tạo button bằng widget button với thuộc tính SWT.PUSH.

quit.setText("Quit");
quit.setBounds(50, 50, 80, 30);

Set text và size cho button

quit.addSelectionListener(new SelectionAdapter() {
    @Override
    public void widgetSelected(SelectionEvent e) {
        shell.getDisplay().dispose();
        System.exit(0);
    }
});

Selection Listener lắng nghe (theo dõi) sự kiên bấm button. Khi người dùng bấm button Quit, hàm widgetSelected() được gọi.
Trong hàm widgetSelected(), chúng ta sẽ giải phóng tài nguyên cho HĐH và kết thúc chương trình.
@Override là 1 chú thích thông báo cho trình biên dịch biết hàm widgetSelected() sẽ được override.

Kết quả:

Java SWT - Button
Java SWT – Button

Be the first to comment

Leave a Reply