Mục lục
Hướng dẫn và ví dụ Java SWT List
Xem thêm các chuyên mục:

Là một website được viết trên công nghệ web Flutter vì vậy hỗ trợ rất tốt cho người học, kể cả những người học khó tính nhất.
Hiện tại website đang tiếp tục được cập nhập nội dung cho phong phú và đầy đủ hơn. Mong các bạn nghé thăm và ủng hộ website mới của chúng tôi.


SWT List là một thành phần giao diện, nó hiển thị danh sách các phần tử (List-item) là các string, và cho phép người dùng chọn một hoặc nhiều phần tử.

Chú ý: SWT List là một thành phần giao diện thông dụng trong một ứng dụng. Nhưng SWT List có một vài nhược điểm sau:
- SWT List chỉ chứa các phần tử (List Item) có kiểu String.
- Các List-Item không thể hiển thị các biểu tượng (icon)
Để khắc phục các nhược điểm trên bạn có thể sử dụng SWT Table để thay thế SWT List.
Các Style có thể áp dụng cho SWT List:
- SWT.BORDER
- SWT.MULTI: Cho phép chọn một hoặc nhiều phần tử (List-item).
- SWT.SINGLE: Chỉ cho phép chọn nhiều nhất 1 phần tử.
- SWT.V_SCROLL: Hiển thị thanh cuộn thẳng đứng
- SWT.H_SCROLL: Hiển thị thanh cuộn nằm ngang.

ListDemo.java
package org.o7planning.swt.list;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Shell;
public class ListDemo {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("SWT List (o7planning.org)");
shell.setSize(450, 200);
RowLayout layout = new RowLayout(SWT.VERTICAL);
layout.spacing = 10;
layout.marginHeight = 10;
layout.marginWidth = 10;
shell.setLayout(layout);
// Tạo một đối tượng List
// (Cho phép chọn nhiều dòng, và hiển thị thanh cuộn thẳng đứng).
final List list = new List(shell, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
list.setLayoutData(new RowData(240, 100));
list.add("Apple");
list.add("Apricot");
list.add("Banana");
list.add("Carrot");
list.add("Cherry");
list.add("Courgette");
list.add("Endive");
list.add("Grape");
Label label = new Label(shell, SWT.NONE);
label.setLayoutData(new RowData(240, SWT.DEFAULT));
list.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
int[] selections = list.getSelectionIndices();
String outText = "";
for (int i = 0; i < selections.length; i++) {
outText += selections[i] + " ";
}
label.setText("You selected: " + outText);
}
});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}