The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.awt  [78 examples] > Text  [3 examples]

e593. 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();
        }
    }

 Related Examples
e591. Drawing Simple Text
e592. Drawing Rotated Text

See also: Colors    Components    Containers    Cursors    Drawing    Events    Focus    Frames    GridBagLayout    Images    Shapes    Simulating Events    The Screen   


© 2002 Addison-Wesley.