您的位置:首页 > 其它

SWT/JFACE表格Table可编辑

2011-08-15 15:13 501 查看
SWT/JFACE表格Table可编辑
2009-10-12 22:52

今天刚好遇到了这个问题写了个例子,。

public class Test {

public static String []NAMES={"周杰伦","王力宏","SHE"};//定义下拉框内的值

public static void main(String[] args) {

Display display=new Display();

Shell shell=new Shell(display);

shell.setLayout(new FillLayout());

//自己写的生成表格的工具类,主要用来生成表格并显示数据,

TableKiller tk=new TableKiller();

tk.setInputType("com.client.util.People", new String[]{"id","name","pass"});

tk.createTable(shell, new String[]{"ID","姓名","密码"});

TableViewer tv=tk.getTableViewer();

//以上是自己写的工具类,下面都一样

tv.setInput(PeopleFactory.getPeoples());

//PeopleFactory.getPeoples()模拟从数据库取出数据,Hibernate的话就是从DAO中得到数据

//以下是表格的编辑程序段

tv.setColumnProperties(new String[]{"id","name","pass"});

//设置每一列的别名,也可以是其他的用来标识某一列

CellEditor []cellEditor=new CellEditor[3];

cellEditor[0]=null;

//设空

cellEditor[1]=new ComboBoxCellEditor(tv.getTable(),NAMES,SWT.READ_ONLY);

//下拉框

cellEditor[2]=new TextCellEditor(tv.getTable());

//text

//设置每一列的单元格编辑组建CellEditor

tv.setCellEditors(cellEditor);

tv.setCellModifier(new MyCellModifier(tv));

//设置表格修改器

//下面的程序可以对Text中内容进行验证,例如只能为数字,等等

Text text=(Text)cellEditor[2].getControl();

text.addVerifyListener(new VerifyListener(){

public void verifyText(VerifyEvent e) {

String inStr=e.text;

if(inStr.length()>0){

System.out.println(inStr);

//自己验证

}

}

});

shell.open();

while (!shell.isDisposed()) {

if (!display.readAndDispatch()) {

display.sleep();

}

}

}

}

//自己创建的修改器,实现ICellModifier 接口

public class MyCellModifier implements ICellModifier {

private TableViewer tv;//传入tableviewer

//构造函数

public MyCellModifier(TableViewer tv){

this.tv=tv;

}

//此方法用来设定是否可以编辑,例如

/**

if(property.equals("name")){//name单元格可以修改

return true;

}else if(property.equals("pass")){//pass单元格不可修改

return true;

}

**/

//可以根据property) 判断是否可以修改

public boolean canModify(Object element,String property) {

return true;

}

//此方法决定单击单元格出现CellEditor时显示什么值

public Object getValue(Object element, String property) {

People p=(People) element;

if(property.equals("name")){

return getNameIndex(p.getName());

}else if(property.equals("pass")){

return p.getPass();

}

throw new RuntimeException("错误的列名"+property);

}

private int getNameIndex(String name){

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

if(Test.NAMES[i].equals(name))

return i;

}

return -1;

}

//从CellEditor取得单元格的值

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;

String newName=Test.NAMES[comboIndex];

p.setName(newName);

}else if(property.equals("pass")){

String pass=(String)value;

if(pass.equals(""))

return;

p.setPass(pass);

}else{

throw new RuntimeException("错误的列名:"+property);

}

tv.update(p, null);//更新在表格上显示

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: