在日常的系统开发中,swt的table以及tree是最常用的两种复杂控件,如果使用最原始的swt中的table,使用起来是比较的繁琐,幸好Eclipse在jface给我们提供了viewer框架,极大地简化了table和tree这两种复杂控件的使用。在最近开发的一个新的模块中,关于table遇到了一个新的case。table的某一列显示的一个百分比,要求在这一列除了显示百分比之外,还要使用渐变的背景,来可视化地显示,效果类似于
花了一点时间终于做出来了,在此跟大家分享一下。具体的做法就是使用GC自己在table上把背景以及单元格中显示的内容给画出来。
1
public 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
显示效果如下