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);
}
}
}