Eclipse设计实现可重用的SWT构件
2007-11-19 10:44:36 来源:论坛整理 作者:翁长河 点击:
本文从创建一个简单的SWT Tree Table开始,引入可重用的用户界面构件这个开发人员普遍关心的问题,然后分析Eclipse的用户界面的一些设计模式,循序渐进的向读者展示了如何设计实现一个精巧的高度可重用的TreeTable构件,最终通过增加一些扩展的功能显示了该构件强大的可扩展能力和灵活性。
TreeTableViewer中需要添加清单14中的代码。
清单14:TreeTableViewer中增加的代码
private TreeTableSorter tableSorter;
protected void initSorters() {
if (fields.length > 0) {
tableSorter = new TreeTableSorter(fields[0]);
setSorter(tableSorter);
}
TreeColumn[] columns = getTree().getColumns();
columns[0].addSelectionListener(new RowSelectionListener());
}
private class RowSelectionListener extends SelectionAdapter {
public void widgetSelected(SelectionEvent e) {
TreeColumn column = (TreeColumn) e.widget;
IField sortField = (IField) column.getData();
Tree tree = column.getParent();
tree.setSortColumn(column);
tableSorter.setSortField(sortField);
int direction = tableSorter.getSortDirection();
if (direction == TreeTableSorter.ASCENDING)
tree.setSortDirection(SWT.UP);
else
tree.setSortDirection(SWT.DOWN);
refresh();
}
} |
然后再新建一个TreeTableSorter 类,代码如清单15所示。
清单15:新建的TreeTableSorter
public class TreeTableSorter extends ViewerSorter {
public static final int ASCENDING = 1;
public static final int DESCENDING = -1;
private IField field;
private int sortDirection = ASCENDING;
public TreeTableSorter(IField field) {
super();
this.field = field;
}
public void setSortField(IField sortField) {
if (this.field == sortField)
sortDirection *= -1;
else {
sortDirection = ASCENDING;
this.field = sortField;
}
}
public IField getSortField() {
return field;
}
public int getSortDirection() {
return sortDirection;
}
public void setSortDirection(int sortDirection) {
this.sortDirection = sortDirection;
}
public int category(Object element) {
return super.category(element);
}
public int compare(Viewer viewer, Object e1, Object e2) {
if (sortDirection == ASCENDING)
return field.compare(e1, e2);
return field.compare(e2, e1);
}
public boolean isSorterProperty(Object element, String property) {
return super.isSorterProperty(element, property);
}
public void sort(Viewer viewer, Object[] elements) {
super.sort(viewer, elements);
}
} |
在TreeTableSorter的compare方法里,我们轻松的调用IField的compare方法就完成了行数据在该列的排序。有过table排序经验的读者一定有过在比较方法区分每一列的数据进行比较,不得不重复的编写那些烦人的“if…else…”代码。而在我们的TreeTableSorter中,每一列的IField可以自己控制排序算法,因此不需要重复针对不同的列做判断,我们只需要为需要排序的列添加