Mega Code Archive

 
Categories / Java Tutorial / SWT 2D Graphics
 

Using FontMetrics to get char width

import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.FontMetrics; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; public class FontMetricsCharWidth {   public static void main(String[] args) {     Display display = new Display();     Shell shell = new Shell(display);     Text text = new Text(shell, SWT.NONE);     GC gc = new GC(text);     FontMetrics fm = gc.getFontMetrics();     int charWidth = fm.getAverageCharWidth();     int width = text.computeSize(charWidth * 8, SWT.DEFAULT).x;     gc.dispose();          System.out.println(width);     shell.isDisposed();     display.dispose();   } }