Getting the dimensions of a text in Swing

This example shows you how to center a text on the JFrame. It will take into account the specifics of the chosen font. Run it from command line like java Main Helvetica.

Main.java:

import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame {
   private String fontname;
   private String text = "Easter Island";
 
   public Main(String fontname) {
      this.fontname = fontname;
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
   } 

   public void paint(Graphics g) {
      super.paint(g);
 
      Graphics2D g2d = (Graphics2D) g;
      Font f = new Font(fontname, Font.BOLD, 36);
      FontMetrics fm = getFontMetrics(f);
 
      int swidth = fm.stringWidth(text);
      int sheight = fm.getAscent();
 
      int width = getSize().width;
      int height = getSize().height;
 
      g2d.setColor(Color.gray);
      g2d.drawLine(0, height/2, width, height/2);
      g2d.drawLine(width/2, 0, width/2, height);
 
      g2d.setColor(Color.black);
      g2d.setFont(f);
      g2d.drawString(text, width/2 - swidth/2, height/2 + sheight/2);
   }
  
   public static void main(String []args) {
      if (args.length == 0) {
         System.err.println("Usage: java Main <fontname>");
         System.exit(1);
      }
 
      Main main = new Main(args[0]);
      main.setVisible(true);
      main.setSize(300, 300);
   }
}