前边实现了一个表格的基本功能,但这并不够好,能否为表格实现一些更好的功能呢?答案是肯定的。下边我们来加入直接编辑的功能。
一、要实现这个功能必须提供一个实现ICellModifier的类。内容如下
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.widgets.TableItem;


public class MyCellModifier implements ICellModifier
{
private TableViewer tv;

public static String[] NAMES =
{"张三","李四","小红","翠花"};

public MyCellModifier(TableViewer tv)
{
this.tv = tv;
}

public boolean canModify(Object element, String property)
{
return true;
}


public Object getValue(Object element, String property)
{
People p = (People)element;

if(property.equals("name"))
{
return new Integer(getNameIndex(p.getName()));

}else if(property.equals("sex"))
{
return new Boolean(p.getSex().equals("男"));

}else if(property.equals("age"))
{
return String.valueOf(p.getAge());
}
throw new RuntimeException("error column name : " + property);
}

private int getNameIndex(String name)
{

for(int i=0;i<NAMES.length;i++)
{

if(NAMES[i].equals(name))
{
return i;
}
}
return -1;
}


public void modify(Object element, String property, Object value)
{
TableItem item = (TableItem)element;
People p = (People)item.getData();

if (property.equals("name"))
{
Integer comboIndex = (Integer)value;

if(comboIndex.intValue() == -1)
{
return ;
}
String newName = NAMES[comboIndex.intValue()];
p.setName(newName);

}else if(property.equals("sex"))
{
Boolean newValue = (Boolean)value;
System.out.println(newValue);

if(newValue.booleanValue())
{
p.setSex("男");

}else
{
p.setSex("女");
}

}else if (property.equals("age"))
{
String newValue = (String)value;

if(newValue.equals(""))
{
return ;
}
Integer newAge = new Integer(newValue);
p.setAge(newAge);

}else
{
throw new RuntimeException("错误列名:" + property);
}
tv.update(p, null);
}
}
二、好了,有了这个类,下一部就是如何把它和TestTableViewer关联起来,在TestTableViewer中setInput()后加入如下内容

tableViewer.setColumnProperties(new String[]
{"id","name","sex","age","createDate"});
CellEditor[] cellEditor = new CellEditor[5];
cellEditor[0] = null;
cellEditor[1] = new ComboBoxCellEditor(tableViewer.getTable(),MyCellModifier.NAMES,SWT.READ_ONLY);
cellEditor[2] = new CheckboxCellEditor(tableViewer.getTable());
cellEditor[3] = new TextCellEditor(tableViewer.getTable());
cellEditor[4] = null;
tableViewer.setCellEditors(cellEditor);
ICellModifier modifier = new MyCellModifier(tableViewer);
tableViewer.setCellModifier(modifier);
我们让名字这一列用下拉条来编辑,让性别这一列变成类似checkbox的操作,让年龄这一类变成直接输入
ok,尝试一下。
三、问题出现,如果年龄的地方我们输入一个非数字呢,所以为了安全起见,我们加入一个验证器,禁止用户输入非数字
在上边的内容下加入
Text text = (Text)cellEditor[3].getControl();

text.addVerifyListener(new VerifyListener()
{

public void verifyText(VerifyEvent e)
{
String inStr = e.text;

if (inStr.length() > 0)
{

try
{
Integer.parseInt(inStr);
e.doit = true;

}catch(Exception ep)
{
e.doit = false;
}
}
}
});
好了,再试试是否不能输入非整数了?解决。其实还是有些问题的,试着输入个0,呵呵。这里就需要你自己按照自己的实际需求来实现了。
但作为demo这个的目的已经达到了。
source下载:
http://www.blogjava.net/Files/dreamstone/jface-3.rar