Java AWT Tutorials

adplus-dvertising
Centering Text in java
Previous Home Next

In this example we are write a text at the center of window in java using font metrics. In this we are using Graphics class and Applet class.

void draw Centered String (String s, int h, int w, Graphics g); This method is used to write text at center.g.draw String (s ,curX, curY);is use for draw string

Font metrics use for mainly two purpose first is to determine the spacing between line of text and the second is to determine the length of the string.

Here first we are importing two packages. Then after we have write applet tag into comments. In this tag we have pass three arguments code ,height and width. The code attribute is used to call the applet class. And Height , width is used for Seizing the window.

Here is an example that centers text, left to right, top to bottom, in a window .Font metrics is use to determine the assent, descent, and the width of the string and compute the position at which it must be displayed to be center.

Example

//Centering text
import java.awt.*;
import java.applet.*;
/*<applet code="CenteringText" width=200 hight=100>
</applet>
*/
public class CenteringText extends Applet
{
final Font f=new Font("SanfAerif",Font.ITALIC,20);
public void paint(Graphics g)
{
Dimension d=this.getSize();
g.setFont (f);
g.setColor(Color.green);
drawCenteredString("This is centered string.",d.width,d.height,g);
}
public void drawCenteredString(String s,int h,int w,Graphics g)
{
FontMetrics fm=g.getFontMetrics();
int X=(w-fm.stringWidth(s))/2;
int Y=(fm.getAscent()+(h-fm.getAscent()+(fm.getDescent()))/2);
g.drawString(s,X,Y);
}}

Output of Example:

Download Source Code

Previous Home Next