Sun Java Solaris Communities My SDN Account Join SDN
 
Code sample

Code Samples from the Java Developers Almanac 2000

 


Code Samples Index

These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms

Getting the Dimensions of Text

 
 // From within the paint() method.
 public void paint(Graphics g) {
   Graphics2D g2d = (Graphics2D)g;
   Font font = new Font("Serif", Font.PLAIN, 12);
   FontMetrics fontMetrics = g2d.getFontMetrics();
     
   int width = fontMetrics.stringWidth("aString");
   int height = fontMetrics.getHeight();
 }
     
 // From within a component.
 class MyComponent extends JComponent {
   MyComponent() {
   Font font = new Font("Serif", Font.PLAIN, 12);
   FontMetrics fontMetrics = getFontMetrics(font);
     
   int width = fontMetrics.stringWidth("aString");
   int height = fontMetrics.getHeight();
   }
 }
 

Examplets provided by permission of the publisher, Addision-Wesley, and Author Patrick Chan.

Order this book from Amazon