Java Centered Text with Underline

May 9, 2011 | AWT Graphics in Java

This code gives strength on AWT graphics programming. There are no predefined methods that can be used straightaway to place the text in the center of the frame and also underline the text. Some programming techniques are required to solve the task.

Example on Java Centered Text with Underline

The following program places the sting in the center (both ways - horizontally and vertically) of the frame and also underline with blue color.

import java.awt.*;
public class CenterAndUnderline extends Frame
{
  public CenterAndUnderline()
  {
    setSize(400, 200);
    setVisible(true);
  } 
  public void paint(Graphics g)
  {                               
    Dimension frameSize = getSize();
    int frameWidth = frameSize.width;
    int frameHeight = frameSize.height;
                                     
    String displayText = "way2java.com";
		
    Font f1 = new Font("DialogInput", Font.BOLD, 20);
    g.setFont(f1);
    FontMetrics fm = getFontMetrics(f1);
			
    int sw = fm.stringWidth(displayText);
                                                     
    int horizontalPos = (frameWidth - sw)/2;
    int verticalPos = frameHeight/2;
    g.drawString(displayText, horizontalPos, verticalPos);

    g.setColor(Color.blue);
    g.drawLine(horizontalPos, verticalPos, horizontalPos+sw, verticalPos);
  }
  public static void main(String args[])
  {
    new CenterAndUnderline();
  }
}

Java Centered Text with Underline Output screen of Java Centered Text with Underline

To get the size of the frame

       Dimension frameSize = getSize();
       int frameWidth = frameSize.width;
       int frameHeight = frameSize.height;

getSize() method of Frame class (inherited from its super class Component) returns the size of the frame as a Dimension object. width and height are the variables of Dimension class that return the width and height of the frame.

To get the width of the string

For this we use FontMetrics class which we used earlier to get the metadata of a font. The width of the string displayText, in pixels, can be obtained using stringWidth() method of it.

       int sw = fm.stringWidth(displayText);

The stringWidth() method of FontMetrics class returns the width of the string, displayText, in pixels.

       int horizontalPos = (frameWidth - sw)/2;
       int verticalPos = frameHeight/2;

The locations horizontalPos and verticalPos correspond to the center point of the frame. The height of the text is taken as negligible.

       g.drawString(displayText, horizontalPos, verticalPos);

Now the text is drawn at the center of the frame with drawstring() method.

            
       g.drawLine(horizontalPos, verticalPos, horizontalPos+sw, verticalPos);

The drawLine() method draws the line on the baseline of the font which becomes automatically underline.