可以使用GC類的getAdvanceWidth(char ch)獲取當(dāng)前字符所占的像素寬度.

public?static?int?getStringWidth(String?string,?Control?control)?
{

??? int?width?=?0;
????GC?gc?=?new?GC(control);

?? ?for?(int?i?=?0;?i?<?string.length();?i++)?
{
????????char?c?=?string.charAt(i);
????????width?+=?gc.getAdvanceWidth(c);
????}

????gc.dispose();
????return?width;
}
或者更通用的,其中string是目標(biāo)字符串,font是你要設(shè)給字符串的字體對象:

public?static?int?getStringWidth(String?string,?Font?font)
{
????int?width?=?0;
????Shell?shell?=?new?Shell();
????Label?label?=?new?Label(shell,?SWT.NONE);
????label.setFont(font);
????GC?gc?=?new?GC(label);

????for(int?i=0;i<string.length();i++)
{
??????????char?c?=?string.charAt(i);
??????????width?+=?gc.getAdvanceWidth(c);
????}
????gc.dispose();
????shell.dispose();
????return?width;
}
getAdvanceWidth
????????? public int getAdvanceWidth(char?ch)
- Returns the advance width of the specified character in the font which is currently selected into the receiver.
The advance width is defined as the horizontal distance the cursor should move after printing the character in the selected font.
- Parameters:
- ch - the character to measure
- Returns:
- the distance in the x direction to move past the character before painting the next
- Throws:
- SWTException -
- ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed
可以如下面的程序使用該函數(shù):


















或者更通用的,其中string是目標(biāo)字符串,font是你要設(shè)給字符串的字體對象:





















