问题描述
ComboBoxViewerCellEditor可以应用在TableViewer,TreeViewer等中,让用户从下拉列表中选值。但是输入的值必须存在下拉列表中,如果不存在,结束编辑后Cell中的值是空字符串(感觉是编辑的值丢了)。原因是因为ComboBoxViewerCellEditor中的value是由StructuredSelection决定的,当用户输入不存在的值时,没有匹配的,StructuredSelection返回empty。
有些情况下,用户需要输入不同的值。例如:下拉列表中值是常用的选项,高级用户可以输入其它的选项。
Solution
继承ComboBoxViewerCellEditor,对其进行扩展,让getValue和setValue与内部CCombo的text进行关联。扩展后的AllowNewValueChbViewerCellEditor的使用方法和ComboBoxViewerCellEditor完全一样。
import org.eclipse.jface.viewers.ComboBoxViewerCellEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.widgets.Composite;
/**
* Extend ComboBoxViewerCellEditor to allow user input value which is not in input list.
* Just use it same like a ComboBoxViewerCellEditor.
*
* @author alzhang
*/
public class AllowNewValueChbViewerCellEditor extends ComboBoxViewerCellEditor {
/**
* Creates a new cell editor with a combo viewer and a default style
*
* @param parent
* the parent control
*/
public AllowNewValueChbViewerCellEditor(Composite parent) {
this(parent, SWT.NONE);
}
/**
* Creates a new cell editor with a combo viewer and the given style
*
* @param parent
* the parent control
* @param style
* the style bits
*/
public AllowNewValueChbViewerCellEditor(Composite parent, int style) {
super(parent, style);
}
@Override
protected void doSetValue(Object value) {
if (!(value instanceof String)) {
throw new IllegalArgumentException("The parameter value should be String.");
}
getComboBox().setText((String) value);
}
@Override
protected Object doGetValue() {
return getComboBox().getText();
}
private CCombo getComboBox() {
return (CCombo) this.getControl();
}
}