SWT Combo和ComboViewer

By | 2018年4月7日

Combo

就是一个下拉列表,但是还可以输入,如果不想允许输入,style添加SWT.READ_ONLY。

Combo combo = new Combo(parent, SWT.NONE);
combo.setItems(new String[] {"Item1", "Item2", "Item3"});
combo.select(0);

int select = combo.getSelectionIndex();

ComboViewer

对Combo的封装,input可以是任何类型,通常会是一个Collection或Array,用ArrayContentProvider就可以了。其它类型input,自己实现ContentProvider。

SWT.READ_ONLY表示不可以输入。

ComboViewer comboViewer = new ComboViewer(parent, SWT.NONE);
comboViewer.setContentProvider(new ArrayContentProvider());

comboViewer.setLabelProvider(new LabelProvider() {
    @Override
    public Image getImage(Object element) {
        return Display.getDefault().getSystemImage(SWT.ICON_INFORMATION);
    }

    @Override
    public String getText(Object element) {
        Student st = (Student) element;
        return String.format("%s - %s", st.getName(), st.getCountry());
    }
});

List students = StudentFactory.create();
comboViewer.setInput(students);
comboViewer.setSelection(new StructuredSelection(students.get(0)));

comboViewer.addSelectionChangedListener(new ISelectionChangedListener() {
    @Override
    public void selectionChanged(SelectionChangedEvent event) {
        StructuredSelection selection = (StructuredSelection) event.getSelection();
        Object firstElement = selection.getFirstElement();
        if (firstElement instanceof Student) {
            // Do something.
        }
    }
});

处理Cmobo输入

去掉SWAT.READ_ONLY,则可以在文本框中输入,对Combo可以添加和Text控件一样的各种事件。

comboViewer.getCombo().addModifyListener(new ModifyListener(){
    @Override
    public void modifyText(ModifyEvent e) {
        System.out.println("Input changed.");
    }
});

comboViewer.getCombo().addKeyListener(new KeyAdapter() {
    @Override
    public void keyPressed(KeyEvent e) {
        if (SWT.CR == e.keyCode) {
            System.out.println("Entery key is pressed.");
        }
    }
});

comboViewer.getCombo().addFocusListener(new FocusAdapter() {
    @Override
    public void focusLost(FocusEvent e) {
        System.out.println("Focus is lost.");
    }
});

comboViewer.getCombo().addVerifyListener(new VerifyListener() {
    @Override
    public void verifyText(VerifyEvent e) {
        // Prevent from inputing letter "s".
        e.doit = !"s".equals(e.text);
    }
});