转自http://www.blogjava.net/kingLv/articles/239354.html
1public class PaintTableCell {
2
3 public static void main(String[] args) {
4 final Display display = Display.getDefault();
5 Shell shell = new Shell(display);
6 shell.setText("Paint Table Cell");
7 shell.setSize(500, 400);
8 shell.setLayout(new FillLayout());
9
10 final Table table = new Table(shell, SWT.FULL_SELECTION | SWT.SINGLE);
11 table.setHeaderVisible(true);
12 table.setLinesVisible(true);
13
14 TableColumn column1 = new TableColumn(table, SWT.NONE);
15 column1.setWidth(100);
16 column1.setAlignment(SWT.LEFT);
17 column1.setText("Column 1");
18
19 TableColumn column2 = new TableColumn(table, SWT.NONE);
20 column2.setWidth(100);
21 column2.setAlignment(SWT.RIGHT);
22 column2.setText("Column 2");
23
24 TableItem item1 = new TableItem(table, SWT.NONE);
25 item1.setText("item 11");
26
27 TableItem item2 = new TableItem(table, SWT.NONE);
28 item2.setText(new String[] {"item 21", "item 22"});
29
30 table.addPaintListener(new PaintListener() {
31
32 @Override
33 public void paintControl(PaintEvent e) {
34 //获得单元格的位置
35 Rectangle rect = table.getItem(0).getBounds(1);
36
37 //计算需要绘制渐变效果的长度
38 int width = rect.width * 67 / 100;//67%
39
40 GC gc = e.gc;
41 //设置GC的背景色和前景色
42 gc.setForeground(new Color(display, 255, 192, 0));
43 gc.setBackground(new Color(display, 255, 230, 151));
44 //绘制渐变效果
45 gc.fillGradientRectangle(rect.x, rect.y, width, rect.height, false);
46
47 //绘制单元格中的文字
48 String text = "item 12";
49 gc.setForeground(display.getSystemColor(SWT.COLOR_BLACK));
50 int pixels = gc.getFontMetrics().getAverageCharWidth() * text.length();
51 gc.drawString(text, rect.x + rect.width - pixels - 6, rect.y, true);
52 }
53
54 });
55
56 shell.open();
57
58 while(!shell.isDisposed()) {
59 if(!display.readAndDispatch()) {
60 display.sleep();
61 }
62 }
63 display.dispose();
64 }
65}
66