Font centered : Font « 2D Graphics GUI « Java






Font centered

Font centered
    

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.JFrame;
import javax.swing.JPanel;

public class HorizontallyCenteredText extends JPanel {
  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));

    paintHorizontallyCenteredText(g2, "Java Source", 200, 75);
    paintHorizontallyCenteredText(g2, "and", 200, 125);
    paintHorizontallyCenteredText(g2, "Support", 200, 175);
  }

  protected void paintHorizontallyCenteredText(Graphics2D g2, String s,
      float centerX, float baselineY) {
    FontRenderContext frc = g2.getFontRenderContext();
    Rectangle2D bounds = g2.getFont().getStringBounds(s, frc);
    float width = (float) bounds.getWidth();
    g2.drawString(s, centerX - width / 2, baselineY);
  }

  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.getContentPane().add(new HorizontallyCenteredText());
    f.setSize(450, 350);
    f.show();
  }
}

           
         
    
    
    
  








Related examples in the same category

1.Ascii font pattern
2.A cache of the dynamically loaded fonts found in the fonts directory
3.Load font from ttf file
4.Outline Font paintOutline Font paint
5.Font paintFont paint
6.Font DerivationFont Derivation
7.Font ListFont List
8.FontDemo lists the system fonts and provides a sample of each one(Have some problems)
9.Finds and displays available fonts
10.Obtain FontMetrics of different fonts
11.Draw font inside a Rectangle
12.Display font in a grid
13.Create font from true type font
14.Wrap string according to FontMetrics
15.Draw base line and enclosing line for a font
16.List all Fonts