表格型树是用TableTreeViewer来实现,自从SWT下的TableTree被废弃之后,其扩展TableTreeViewer也成了鸡肋,不再被建议使用,既然Tree可以实现表格型树,那么其扩展TreeView当然也没有问题,用TreeViewer实现的表格型树,之前的TreeViewer实例菜单的呢过功能代码不用做任何修改.
修改的不多,一是在主程序为树加上几列对象TreeColumn,二是创建一个新的表格型树的标签器,关于TreeColumn在Tree组件的时候有此内容的讲解.这个地方和之前一样.
TreeViewer3.java
public class TreeViewer3 {
public static void main(String[] args) {
new TreeViewer3().open();
} public void open() {
final Display display = new Display();
final Shell shell = new Shell();
shell.setSize(300, 300);
// -----------界面核心代码-------------------
shell.setLayout(new FillLayout());
TreeViewer tv = new TreeViewer(shell, SWT.BORDER); Tree tree = tv.getTree();
tree.setHeaderVisible(true);
TreeColumn column = new TreeColumn(tree, SWT.LEFT);
column.setText("名称");
column.setWidth(150);
column = new TreeColumn(tree, SWT.LEFT);
column.setText("子结点数");
column.setWidth(80);
column = new TreeColumn(tree, SWT.LEFT);
column.setText("性别");
column.setWidth(40); tv.setContentProvider(new TreeViewerContentProvider());
tv.setLabelProvider(new MyTableLableProvider());
// 和TableViewer一样,数据的入口也是setInput方法
List<Country> input = (List)DataFactory.createTreeData();
tv.setInput(input);
// --------------插入代码:START------------------
MyActionGroup actionGroup = new MyActionGroup(tv);// 生成一个ActionGroup对象
actionGroup.fillContextMenu(new MenuManager());// 将按钮注入到菜单对象中
// -----------END------------------
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
标签器换了一个,它必须实现ITableLabelProvider接口.
public class MyTableLableProvider implements ITableLabelProvider {
public String getColumnText(Object element, int columnIndex) {
ITreeEntry entry = (ITreeEntry) element;
switch (columnIndex) {
case 0:
return entry.getName();
case 1:
List list = entry.getChildren();
if (list == null)
return "";
return String.valueOf(list.size());
case 2:
if (entry instanceof People) {
boolean sex = ((People) entry).isSex();
return sex ? "男" : "女";
}
return "";
default:
return "";
}
} public Image getColumnImage(Object element, int columnIndex) {
return null;
}
public void addListener(ILabelProviderListener listener) {}
public void removeListener(ILabelProviderListener listener) {}
public void dispose() {}
public boolean isLabelProperty(Object element, String property) {
return false;
}
}