`
louisling
  • 浏览: 140707 次
  • 性别: Icon_minigender_1
  • 来自: ZhuHai
社区版块
存档分类
最新评论

SWT组件Table 的排序

    博客分类:
  • RCP
阅读更多
/**
 * This util calss provides some general RCP methods
 * 
 * @author Louis
 */
public class RcpUtils {
    /**
     * Add sorter to the specified column, compares using Collator
     */
    public static void addSorter(final Table table, final TableColumn column) {
        column.addListener(SWT.Selection, new Listener() {
            boolean isAscend = true;
            Collator comparator = Collator.getInstance(Locale.getDefault());

            public void handleEvent(Event e) {
                int columnIndex = getColumnIndex(table, column);
                TableItem[] items = table.getItems();

                for (int i = 1; i < items.length; i++) {
                    String value2 = items[i].getText(columnIndex);
                    for (int j = 0; j < i; j++) {
                        String value1 = items[j].getText(columnIndex);
                        boolean isLessThan = comparator.compare(value2, value1) < 0;
                        if ((isAscend && isLessThan) || (!isAscend && !isLessThan)) {
                            String[] values = getTableItemText(table, items[i]);
                            Object obj = items[i].getData();
                            items[i].dispose();

                            TableItem item = new TableItem(table, SWT.NONE, j);
                            item.setText(values);
                            item.setData(obj);
                            items = table.getItems();
                            break;
                        }
                    }
                }

                table.setSortColumn(column);
                table.setSortDirection((isAscend ? SWT.UP : SWT.DOWN));
                isAscend = !isAscend;
            }
        });
    }

    public static int getColumnIndex(Table table, TableColumn column) {
        TableColumn[] columns = table.getColumns();
        for (int i = 0; i < columns.length; i++) {
            if (columns[i].equals(column))
                return i;
        }
        return -1;
    }

    public static String[] getTableItemText(Table table, TableItem item) {
        int count = table.getColumnCount();
        String[] strs = new String[count];
        for (int i = 0; i < count; i++) {
            strs[i] = item.getText(i);
        }
        return strs;
    }
}

//默认使用字符串排序, 使用方法:
//RcpUtils.addSorter(table, column1);
//RcpUtils.addSorter(table, column2);
2
2
分享到:
评论
2 楼 muzibaishui2006 2012-08-09  
用的挺方便的,十分感谢!
1 楼 wxpuc123 2011-04-13  
谢了,正好用到。

相关推荐

Global site tag (gtag.js) - Google Analytics