1,简单显示,表格的式样见注释中的内容
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;

public class TestTableViewer
{
private static Table table;
/**
* Launch the application
* @param args
*/
public static void main(String[] args) {
final Display display = Display.getDefault();
final Shell shell = new Shell();
shell.setSize(500, 375);
shell.setText("SWT Application");
//注意这里,SWT.NULTI代表可以选择多行,SWT.FULL_SELECTION代表可以整行选择,SWT.BORDER边框,SWT.V_SCROLL ,SWT.H_SCROLL滚动条
final TableViewer tableViewer = new TableViewer(shell, SWT.MULTI | SWT.FULL_SELECTION | SWT.BORDER|SWT.V_SCROLL|SWT.H_SCROLL);
table = tableViewer.getTable();
table.setLinesVisible(true); //注意,若没有这句则没有分割的横竖线线。
table.setHeaderVisible(true); //若没有这句,则没有分割的名字。
table.setBounds(97, 79, 373, 154);

final TableColumn newColumnTableColumn = new TableColumn(table, SWT.NONE);
newColumnTableColumn.setWidth(39);
newColumnTableColumn.setText("ID");

final TableColumn newColumnTableColumn_1 = new TableColumn(table, SWT.NONE);
newColumnTableColumn_1.setWidth(85);
newColumnTableColumn_1.setText("姓名");
final TableColumn newColumnTableColumn_2 = new TableColumn(table, SWT.NONE);
newColumnTableColumn_2.setWidth(41);
newColumnTableColumn_2.setText("性别");

final TableColumn newColumnTableColumn_3 = new TableColumn(table, SWT.NONE);
newColumnTableColumn_3.setWidth(43);
newColumnTableColumn_3.setText("年龄");

final TableColumn newColumnTableColumn_4 = new TableColumn(table, SWT.NONE);
newColumnTableColumn_4.setWidth(126);
newColumnTableColumn_4.setText("创建日期");
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
}
2,加入布局
显示的效果不好,我们要加入布局,让view填充整个画面在shell.open()后加上
ok,效果达到
3,为TableViewer加上数据,光突突的样子不好看。这里是demo所以不再从数据库里边取数据了。自己构造一个List用来做数据。实际使用中也是这么使用,不过不同的是这里是随意构造的list,而显示实际使用中是从数据库取出数据构造list.
(1)构造一个people类,同时给People类提供一个构造假数据的方法getPeople()
(2)给tableViewer提供内容器(IStructuredContentPorvider)和标签器(ITableLabelProvider)
如果想一个tableviewer显示数据,那必须给它提供内容器和标签器,内容器的作用是从List(也可以是其他的集合类)中提取出一个对象(例如People对应着表格的一行,数据库的一条记录),标签器的作用是从一个对象中提取出一个字段(例如年龄,对应着表格中的一个单元格,数据库中某一列的一个值)下边是内容器和标签器的代码:
内容器:
标签器:
注意这里:extends LabelProvider,为什么要加这个呢? 因为如果不加这个,因为实现 ITableLabelProvider 的缘故我们还要写四个空函数,而我们本身不需要在这四个空函数中实现什么,所以让它继承自LabelProvider,就可以避免四个空函数。
(3)把标签器和内容器给tableviewer
在shell.open()前边加上这几行
//设置内容器

tableViewer.setContentProvider(
new ContentProvider());
//设置标签器

tableViewer.setLabelProvider(
new TableLabelProvider());
//把数据集合给tableView

tableViewer.setInput(People.getPeople());
//这样利用内容器和标签器就能从setInput得到的数据集合分解出显示表格需要的数据。这是一个典型的mvc的实现.
4,样式改变
如果想在每一列前加入一个checkbox
只需要在开始的式样中加入SWT.CHECK
好了到此一个简单的样子选择出来了,但这仅仅是开始,下边将继续介绍按列排序、过滤器、行的颜色设置、在表格上直接编辑等功能
附上source:http://www.blogjava.net/Files/dreamstone/jface-1.rar
效果图:
