EclipseRCP中为表格加上序号列

需求如题,效果如下:

 


具体代码如下:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.TableItem;

public class ItemsNumberForTable {

    private static HashMap numberLabelForTableViewer = new HashMap();
    public static void setItemsNumber(TableViewer tableViewer){
        List numberLabel = new ArrayList();
        List oldNumberLabel = (List)getNumberLabelForTableViewer().get(tableViewer);
        if(oldNumberLabel!=null){
            for(Iterator iter = oldNumberLabel.iterator();iter.hasNext();){
                CLabel cLabel = (CLabel)iter.next();
                cLabel.dispose();
            }
        }
        Image image = new Image(Display.getDefault(), 1, 15);
        TableItem[] tableItem = tableViewer.getTable().getItems();
        TableEditor te[] = new TableEditor[tableItem.length];   
        for (int i = 0; i < tableItem.length; i++) {
            te[i] = new TableEditor(tableViewer.getTable());
            te[i].horizontalAlignment = SWT.CENTER;
            te[i].grabHorizontal = true;
            final CLabel lbl = new CLabel(tableViewer.getTable(), SWT.SHADOW_OUT);
            lbl.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
            lbl.setAlignment(SWT.CENTER);
            lbl.setEnabled(false);
            lbl.setText("" + (i+1));
            te[i].setEditor(lbl, tableItem[i], 0);
            tableItem[i].setImage(image);
            numberLabel.add(lbl);
        }
        numberLabelForTableViewer.put(tableViewer, numberLabel);
    }
    private static HashMap getNumberLabelForTableViewer(){
        return numberLabelForTableViewer;
    }
}

在tableViewer的setInput之后调用ItemsNumberForTable.setItemsNumber(tableViewer)即可

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/kevin99zhang/archive/2008/01/02/2010071.aspx

你可能感兴趣的:(EclipseRCP中为表格加上序号列)