可以使用GC类的getAdvanceWidth(char ch)获取当前字符所占的像素宽度.
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是目标字符串,font是你要设给字符串的字体对象:
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
可以如下面的程序使用该函数:


















或者更通用的,其中string是目标字符串,font是你要设给字符串的字体对象:






















