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

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.