Java SWT – Combobox

Combobox là đối tượng cho phép user lựa chọn 1 item từ 1 list drop-down.

File ComboEx.java

package vncoding;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;



public class ComboEx {

    private Label label;
    
    public ComboEx(Display display) {
        initUI(display);
    }

    private void initUI(Display display) {

        Shell shell = new Shell(display, SWT.SHELL_TRIM | SWT.CENTER);

        RowLayout layout = new RowLayout(SWT.VERTICAL);
        layout.marginLeft = 50;
        layout.marginTop = 30;
        layout.spacing = 30;
        shell.setLayout(layout);

        Combo combo = new Combo(shell, SWT.DROP_DOWN);
        combo.add("Tea");
        combo.add("Coffee");
        combo.add("Orange juice");
        combo.add("Lemon juice");
        combo.add("Wine");
        combo.setLayoutData(new RowData(150, -1));

        label = new Label(shell, SWT.LEFT);
        label.setText("...");   

        combo.addListener(SWT.Selection, event -> onSelected(combo));

        shell.setText("Combo");
        shell.setSize(300, 250);
        shell.open();

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }
    
    private void onSelected(Combo combo) {
        
        label.setText(combo.getText());
        label.pack();        
    }

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

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

Giải thích:
Ví dụ này, là sự kết hợp của 2 đối tượng Combobox và Label. Combobox là 1 list 5 loại đồ uống.

Combo combo = new Combo(shell, SWT.DROP_DOWN);

Tạo combobox với tham số SWT.DROP_DOWN

 

combo.add("Tea");
combo.add("Coffee");
combo.add("Orange juice");
combo.add("Lemon juice");
combo.add("Wine");

Fill dữ liệu cho combobox.

 

combo.addListener(SWT.Selection, event -> onSelected(combo));

Lắng nghe sự kiện user lựa chọn 1 item từ combobox. Khi đó, hàm onSelected() được gọi.

 

label.setText(combo.getText());

Hàm getText() lấy text khi user select trên combobox. Hàm setText() hiển thị text lên Label.

Kết quả:

Java SWT - Combobox
Java SWT – Combobox

Be the first to comment

Leave a Reply