import java.util.Arrays;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class ComboSortList {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
String[] ITEMS = { "A", "B", "C", "D", "E", "F" };
Arrays.sort(ITEMS);
final Combo combo = new Combo(shell, SWT.DROP_DOWN);
combo.setItems(ITEMS);
combo.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
System.out.println("Selected index: " + combo.getSelectionIndex() + ", selected item: "
+ combo.getItem(combo.getSelectionIndex()) + ", text content in the text field: "
+ combo.getText());
}
public void widgetDefaultSelected(SelectionEvent e) {
System.out.println("Default selected index: "
+ combo.getSelectionIndex()
+ ", selected item: "
+ (combo.getSelectionIndex() == -1 ? "<null>" : combo
.getItem(combo.getSelectionIndex())) + ", text content in the text field: "
+ combo.getText());
String text = combo.getText();
if (combo.indexOf(text) < 0) { // Not in the list yet.
combo.add(text);
// Re-sort
String[] items = combo.getItems();
Arrays.sort(items);
combo.setItems(items);
}
}
});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
The org.eclipse.swt.custom.CCombo class can also be used to create combo boxes.CCombos are usually used inside table cells.