Mega Code Archive

 
Categories / Java Tutorial / 2D Graphics
 

Center text based on font metrics

// This example is from the book _Java AWT Reference_ by John Zukowski. // Written by John Zukowski.  Copyright (c) 1997 O'Reilly & Associates. // You may study, use, modify, and distribute this example for any purpose. // This example is provided WITHOUT WARRANTY either expressed or import java.awt.Dimension; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Insets; import javax.swing.JFrame; import javax.swing.JPanel; public class Center extends JPanel {     static String text[] = new String[]{"asdf","asdfasdf"};     private Dimension dim;     public void addNotify() {         super.addNotify();         int maxWidth = 0;         FontMetrics fm = getFontMetrics(getFont());         for (int i=0;i<text.length;i++) {             maxWidth = Math.max (maxWidth, fm.stringWidth(text[i]));         }         Insets inset = getInsets();         dim = new Dimension (maxWidth + inset.left + inset.right,             text.length*fm.getHeight() + inset.top + inset.bottom);         setSize (dim);     }     public void paint (Graphics g) {         g.translate(100, 100);         FontMetrics fm = g.getFontMetrics();         for (int i=0;i<text.length;i++) {             int x,y;             x = (getWidth() - fm.stringWidth(text[i]))/2;             y = (i+1)*fm.getHeight()-1;             g.drawString (text[i], x, y);         }        }     public static void main(String[] a){       JFrame f = new JFrame();       f.add(new Center());       f.setSize(300,300);       f.setVisible(true);     }  }