Paint centered fonts in Java

Description

The following code shows how to paint centered fonts.

Example


import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
/*from  w w  w  .  ja  v a 2 s  .  c  o m*/
import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas extends JComponent {
  public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);

    g2.setFont(new Font("Serif", Font.PLAIN, 48));

    paintHorizontallyCenteredText(g2, "java2s.com", 200, 75);
    paintHorizontallyCenteredText(g2, "abc", 200, 125);
    paintHorizontallyCenteredText(g2, "code", 200, 175);
  }

  protected void paintHorizontallyCenteredText(Graphics2D g2, String s,
      float centerX, float baselineY) {
    FontRenderContext frc = g2.getFontRenderContext();
    Rectangle2D bounds = g2.getFont().getStringBounds(s, frc);
    float width = (float) bounds.getWidth();
    g2.drawString(s, centerX - width / 2, baselineY);
  }
}

public class Main {
  public static void main(String[] a) {
    JFrame window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setBounds(30, 30, 450, 450);
    window.getContentPane().add(new MyCanvas());
    window.setVisible(true);
  }
}

The code above generates the following result.

Paint centered fonts in Java




















Home »
  Java Tutorial »
    Graphics »




Animation
BufferedImage
Color
Font
Gradient
Graphics Settings
Image
Mouse Draw
Print
Shape
Text
Transform