一提到表格,人们就想得到EXCEL。不错,这个优秀的软件一共提供了几千个功能点,但人们平常一般只用到其常用的几十个功能。
SWT/JFACE提供的表格虽然不能完成EXCEL的所有功能,但其常用的功能已经具备。比如:双击编辑表格、操作单元格、在单元格中加入控件。
其关键就在于CellEditor的使用!
for (int i=0; i<items.length; i++) {
TableEditor editor = new TableEditor (table);
CCombo combo = new CCombo (table, SWT.NONE);
combo.setText("CCombo");
combo.add("item 1");
combo.add("item 2");
editor.grabHorizontal = true;
editor.setEditor(combo, items[i], 0);
editor = new TableEditor (table);
Text text = new Text (table, SWT.NONE);
text.setText("Text");
editor.grabHorizontal = true;
editor.setEditor(text, items[i], 1);
editor = new TableEditor (table);
Button button = new Button (table, SWT.CHECK);
button.pack ();
editor.minimumWidth = button.getSize ().x;
editor.horizontalAlignment = SWT.LEFT;
editor.setEditor (button, items[i], 2);
}
用以上代码加入CCombo和Check。
关键在于:
editor.setEditor(combo, items[i], 0);
combo为控件对象,item[i]和0为确定editor(单元格)的位置。
有了这个函数就可以任意加控件了。特殊情况加入text控件就可实现双击编辑,代码如下:
table.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
// Clean up any previous editor control
Control oldEditor = editor.getEditor();
if (oldEditor != null) oldEditor.dispose();
// Identify the selected row
TableItem item = (TableItem)e.item;
if (item == null) return;
// The control that will be the editor must be a child of the Table
Text newEditor = new Text(table, SWT.NONE);
newEditor.setText(item.getText(EDITABLECOLUMN));
newEditor.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent me) {
Text text = (Text)editor.getEditor();
editor.getItem().setText(EDITABLECOLUMN, text.getText());
}
});
newEditor.selectAll();
newEditor.setFocus();
editor.setEditor(newEditor, item, EDITABLECOLUMN);
}
});
哈哈 这样就可以了哦!