Java SWT – Checkbox

Checkbox là 1 button đặc biệt. Checkbox có 2 trạng thái ON/OFF. User có thể dùng chuột để click vào checkbox để check hoặc uncheck.

File CheckButtonEx.java

package vncoding;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class CheckButtonEx {
    
    private Shell shell;

    public CheckButtonEx(Display display) {
        initUI(display);
    }

    private void initUI(Display display) {

        shell = new Shell(display);
        RowLayout layout = new RowLayout();
        layout.marginLeft = 30;
        layout.marginTop = 30;
        shell.setLayout(layout);

        Button cb = new Button(shell, SWT.CHECK);
        cb.setText("Show title");
        cb.setSelection(true);
        
        cb.addListener(SWT.Selection, event -> onButtonSelect(cb));

        shell.setText("Check button");
        shell.setSize(250, 200);
        shell.open();

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }
    
    private void onButtonSelect(Button cb) {

        if (cb.getSelection()) {
            shell.setText("Check button");
        } else {
            shell.setText("");
        }        
    }

    @SuppressWarnings("unused")
    public static void main(String[] args) {

        Display display = new Display();
        CheckButtonEx ex = new CheckButtonEx(display);
        display.dispose();
    }
}

Giải thích:

Title windows phụ thuộc vào trạng thái của checkbox. Title được show khi trạng thái của checkbox là ON, và ngược lại.

Button cb = new Button(shell, SWT.CHECK);
cb.setText("Show title");

Checkbox button được tạo bằng cách truyền đối số SWT.CHECK cho hàm tạo Button(). Phương thức setText() đặt tên cho checkbox.

cb.setSelection(true);

Trạng thái default của checkbox là ON (check). Nếu muốn trạng thái ban đầu của checkbox là OFF (uncheck), thay true bằng false (cb.setSelection(false)).

cb.addListener(SWT.Selection, event -> onButtonSelect(cb));

Lắng nghe sự kiện checkbox được check hay uncheck. Sau đó, sự kiện này được xử lí trong phương thức onButtonSelect().

private void onButtonSelect(Button cb) {
    if (cb.getSelection()) {
        shell.setText("Check button");
    } else {
        shell.setText("");
    }        
}

Phương thức onButtonSelect() trả về true nếu checkbox được check, trả về false nếu check box là uncheck. Title của windows được set bằng phương thức setText().

Kết quả:

Checkbox
Checkbox

Be the first to comment

Leave a Reply