Using FontMetrics to get char width : Font « SWT 2D Graphics « Java Tutorial






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();
  }
}








18.13.Font
18.13.1.Creating Fonts
18.13.2.Font TerminologyFont Terminology
18.13.3.Changing FontsChanging Fonts
18.13.4.Using FontMetrics to get char width
18.13.5.Get system default fontGet system default font