Java Centered Text with Underline

Java Centered Text with Underline

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.


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

To get the size of the frame

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.

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

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

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *