javageometryappletappletviewer

How to place text inside a circle in java applet such that middle of the text comes at the center


I'm trying to write a code to place a text in the middle of a circle such that the center of the string is on the center of the circle. But the text appears to start from the center , if the font size of the string and the diameter of the circle are large. Here is my code,

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.*;
//extending Applet class is necessary
public class Main extends Applet{
public void paint(Graphics g)
    {
        g.setColor(Color.yellow);
        int diameter=500;
        int xpos=100,ypos=100;
        g.fillOval(xpos,ypos,diameter,diameter);
        Font f1 = new Font("Arial",Font.BOLD,24);
        g.setColor(Color.black);
        g.setFont(f1);
        String s="Text inside a circle";
        g.drawString(s,xpos+(diameter/2)-(s.length()/2),ypos+(diameter/2));

    }
}

This is the output I'm getting:

https://i.sstatic.net/ZebQT.png

But I want text to be in the middle.


Solution

  • But the text appears to start from the center

    The length of the String variable only returns the number of characters in the String, not the width (in pixels) of the String.

    You need to know the width of the text in pixels so it can be centered in the circle. For this you use the FontMetrics class.

    FontMetrics fm = g.getFontMetrics();
    int width = fm.stringWidth(s);
    int offset = (diameter - width ) / 2;
    g.drawString(s, xpos + offset, ypos + (diameter / 2));
    //g.drawString(s,xpos+(diameter/2)-(s.length()/2),ypos+(diameter/2));
    

    Note the above will only center based on the width. You should also center based on the height. For this you can use the getStringBounds(...) method. This will allow you to better approximated the vertical centering as well. This will return a Rectangle so you could use the width and height of the Rectangle for both the horizontal and vertical centering.