Java AWT FontMetrics center text

Description

Java AWT FontMetrics center text

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

class Demo extends JPanel {
   final Font f = new Font("SansSerif", Font.BOLD, 18);

   public void paint(Graphics g) {
     Dimension d = this.getSize();

     g.setColor(Color.white);// w  w  w. j a va  2 s.co m
     g.fillRect(0, 0, d.width,d.height);
     g.setColor(Color.black);
     g.setFont(f);
     drawCenteredString("This is centered.", d.width, d.height, g);
     g.drawRect(0, 0, d.width-1, d.height-1);
   }

   public void drawCenteredString(String s, int w, int h,
                                  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);
   }
}

public class Main {
   public static void main(String[] args) {
      Demo panel = new Demo();

      JFrame application = new JFrame();

      application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      application.add(panel);
      application.setSize(250, 250);
      application.setVisible(true);
   }
}



PreviousNext

Related