Font: getStringBounds(String str, FontRenderContext frc) : Font « java.awt « Java by API






Font: getStringBounds(String str, FontRenderContext frc)

 
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;

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

public class MainClass {
  public static void main(String[] args) {
    JFrame jf = new JFrame("Demo");
    Container cp = jf.getContentPane();
    MyCanvas tl = new MyCanvas();
    cp.add(tl);
    jf.setSize(300, 200);
    jf.setVisible(true);
  }
}

class MyCanvas extends JComponent {

  public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g2.setFont(new Font("Serif", Font.PLAIN, 48));

    FontRenderContext frc = g2.getFontRenderContext();
    String s = "www.java2s.com";
    Rectangle2D bounds = g2.getFont().getStringBounds(s, frc);
    float width = (float) bounds.getWidth();
    int centerX = 100;
    int baselineY = 70;
    g2.drawString(s, centerX - width / 2, baselineY);
  }
}


           
         
  








Related examples in the same category

1.Font.PLAIN
2.Font.BOLD | Font.ITALIC
3.Font.BOLD
4.Font.ITALIC
5.Font.TRUETYPE_FONT
6.new Font(String name, int style, int size)
7.Font: createFont(int fontFormat, InputStream fontStream)
8.Font: createGlyphVector(FontRenderContext frc, String str)
9.Font: deriveFont(int style, float size)
10.Font: getFamily()
11.Font: getFontName()
12.Font: getLineMetrics(String str, FontRenderContext frc)
13.Font: getName()
14.Font: getStyle()
15.Font: getSize()