Advanced drawing: Center Text

  1. Problem: Center a Text string in a window automatically:
  2. The solution:

    Programming the solution is tricky and educational...

  3. Sub-Problem 1: find the width and height of the applet window

    The   instance method   getWidth()   returns the width of the Applet window.

    The   instance method   getHeight()   returns the height of the Applet window.

  4. Sub-Problem 2: find the width and height of the display text

    • The class   TextLayout   contains 2 instance methods to measure the dimensions of a String.

    • To measure the size of a String, you need to construct a TextLayout object first:
       TextLayout myLayout = new TextLayout(String, Font, GrphContext);
      • String is the string you want to measure
      • Font is the font
      • GrphContext is the graphical context of the Applet

    • Use:
       FontRenderContext GrphContext = g2.getFontRenderContext();
      to obtain the graphical context of the Applet

  5. Measuring Text:

    • myLayout.getAdvance() returns the "width" of the text

    • myLayout.getAscend() + myLayout.getDescend() is the "height" of the text

  6. The complete solution:

    public class FontApplet extends Applet
    {  public void paint(Graphics g)
          Graphics2D g2 = (Graphics2D)g;
          // select the font into the graphics context
          Font myFont = new Font("Serif", Font.BOLD, 48);
          // This is the string that we want to center --------------
          String message = "Applet";
          // create a text layout to measure the string
          FontRenderContext GrphContext = g2.getFontRenderContext();
          TextLayout layout = new TextLayout(message, myFont, GrphContext);
          // measure the message width and height
          float xMessageWidth  = layout.getAdvance();
          float yMessageHeight = layout.getAscent() + layout.getDescent();
          // center the message in the window
          float xLeft  = 0.5F * (getWidth()  - xMessageWidth);
          float yLower = 0.5F * (getHeight() + yMessageHeight);
          float yBase  = yLower - layout.getDescent();
          // FINALLY... draw the message with first char starting at (xLeft, yBase)
          g2.drawString(message, xLeft, yBase);

    NOTE:   getWidth()   is actually   this.getWidth()
    (ditto for   getHeight())

    this is the Applet, which is a Panel   (see Applet doc: click here)

    Source code is here: click here

  7. The result in a 400x300 window:

  8. Same applet, in a 600x400 window: