calls stringWidth (String) to center several text messages : Font Metrics « 2D Graphics « Java Tutorial






calls stringWidth (String) to center several text messages
import java.awt.FontMetrics;
import java.awt.Graphics;

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

public class FontMetricsStringWidth extends JPanel {

  public static void main(String[] a) {
    JFrame f = new JFrame();
    f.setSize(400, 400);
    f.add(new FontMetricsStringWidth());
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
  }

  public void paint(Graphics g) {
    String[] msgs = { "AAAAAAAAA", "VVVVVVVVVVVVVVVVV", "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" };

    FontMetrics fm = g.getFontMetrics();

    for (int i = 0; i < msgs.length; i++) {
      int x = (getSize().width - fm.stringWidth(msgs[i])) / 2;
      int y = fm.getHeight() * (i + 1);

      g.drawString(msgs[i], x, y);
    }
  }
}








16.24.Font Metrics
16.24.1.Font Metrics: the wealth of dimensional data about a font
16.24.2.Font base line
16.24.3.Getting Char with based on current font
16.24.4.calls stringWidth (String) to center several text messagescalls stringWidth (String) to center several text messages
16.24.5.Center text.Center text.
16.24.6.Draw text to the leftDraw text to the left
16.24.7.Draw text to the rightDraw text to the right
16.24.8.Draw text to the centerDraw text to the center
16.24.9.Text justifyText justify
16.24.10.Draw font metrics
16.24.11.Display a text in 3 dimensions
16.24.12.Obtain FontMetrics of different fonts