在大多數編程工具中都會有這樣的功能,輸入了在工具中特定的關鍵字后,會以其它顏色或加粗顯示。這個功能對將枯燥的程序代碼變的清晰易讀。
Eclipse中當然也包含這個功能。我們知道,Eclipse是以SWT為基礎建立起來的,那么我們是不是也可以利用SWT來實現這個功能呢?
StyledText--這是SWT包中的一個基礎組件,就如同它的名字定義的那樣,可以在它之以前顯示各種樣式的字體。如下代碼:
?1
//
?創建一個帶滾動條的文本框
?2
StyledText?text?
=
?
?3
????
new
?StyledText(
?4
????????shell,
?5
????????SWT.WRAP
?6
????????
|
?SWT.BORDER
?7
????????
|
?SWT.H_SCROLL
?8
????????
|
?SWT.V_SCROLL);
?9
10
//
?設置要顯示的文字
11
text.setText(
"
歡迎光臨六月天
"
);
12
13
//
?加粗顯示“六月天”三個字
14
this
.txtContext.setStyleRange(getHighlightStyle(
4
,?
"
六月天
"
.length()));
15
16
/**?*/
/**
17
*?取加粗文字對象
18
*?
@param
?startOffset
19
*?
@param
?length
20
*?
@return
?StyleRange
21
*/
22
private
?StyleRange?getHighlightStyle(
int
?startOffset,?
int
?length)?
{
23
????StyleRange?styleRange?
=
?
new
?StyleRange();
24
????styleRange.start?
=
?startOffset;
25
????styleRange.length?
=
?length;
26
????
27
????styleRange.fontStyle?
=
?SWT.BOLD;
28
????
29
????
return
?styleRange;
30
}
31
32
當然,我們也可以象Eclipse中那樣,改變文字顏色:
33
34
?程序代碼
35
//
?將“六月天”三個字改為藍色顯示
36
this
.txtContext.setStyleRange(
37
????getColorStyle(
4
,?
"
六月天
"
.length(),?
38
????
this
.shell.getDisplay().getSystemColor(SWT.COLOR_BLUE)));
39
40
/**?*/
/**
41
*?取文字顏色對象
42
*?
@param
?startOffset
43
*?
@param
?length
44
*?
@param
?color
45
*?
@return
46
*/
47
private
?StyleRange?getColorStyle(
int
?startOffset,?
int
?length,?Color?color)?
{
48
????StyleRange?styleRange?
=
?
new
?StyleRange(startOffset,?length,?color,?
null
);
49
????styleRange.fontStyle?
=
?SWT.BOLD;
50
????
return
?styleRange;
51
}
52
除此之外,我們還可以改變文字的背景色,及加下劃線,刪除線等。
雖然StyledText為我們提供了如此多的文字風格,但總覺得還缺少對圖像的支持。不過聽說,Eclipse3.2版的SWT已經提供了對圖像的支持。改天試試。