Getting the Dimensions of Text : Text « 2D Graphics GUI « Java





Getting the Dimensions of Text

   

import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JComponent;
import javax.swing.JFrame;

public class BasicDraw {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.add(new MyComponent());

    frame.setSize(300, 300);
    frame.setVisible(true);
  }

}

class MyComponent extends JComponent {
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    FontMetrics fontMetrics = g2d.getFontMetrics();

    int width = fontMetrics.stringWidth("aString");
    int height = fontMetrics.getHeight();
    System.out.println(width);
    System.out.println(height);
  }

}

   
    
    
  










Related examples in the same category

1.Create a shadowed text
2.Draw 2D Text
3.Drawing Simple Text
4.Drawing Rotated Text
5.Draw string rotated clockwise 45 degrees
6.Draw string rotated counter-clockwise 45 degrees
7.Display underlined text
8.Display vertical text
9.Use AffineTransform to draw vertical text
10.Have a Label with underlined text
11.Display some lyrics on the panel.
12.Display unicode text
13.drawString(): specify the position of the text on the window areadrawString(): specify the position of the text on the window area
14.Rotate a line of character (String)
15.Generate Shape From Text