Center text. : Font Metrics « 2D Graphics « Java Tutorial

Home
Java Tutorial
1.Language
2.Data Type
3.Operators
4.Statement Control
5.Class Definition
6.Development
7.Reflection
8.Regular Expressions
9.Collections
10.Thread
11.File
12.Generics
13.I18N
14.Swing
15.Swing Event
16.2D Graphics
17.SWT
18.SWT 2D Graphics
19.Network
20.Database
21.Hibernate
22.JPA
23.JSP
24.JSTL
25.Servlet
26.Web Services SOA
27.EJB3
28.Spring
29.PDF
30.Email
31.J2ME
32.J2EE Application
33.XML
34.Design Pattern
35.Log
36.Security
37.Apache Common
38.Ant
39.JUnit
Java Tutorial » 2D Graphics » Font Metrics 




Center text.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;

import javax.swing.JFrame;

public class CenterTextRectangle extends JFrame {

  public static void main(String[] a) {
    CenterTextRectangle f = new CenterTextRectangle();
    f.setSize(300300);
    f.setVisible(true);
  }

  final Font f = new Font("SansSerif", Font.BOLD, 18);

  public void paint(Graphics g) {
    Dimension d = this.getSize();

    g.setColor(Color.white);
    g.fillRect(00, d.width, d.height);
    g.setColor(Color.black);
    g.setFont(f);
    drawCenteredString("This is centered.", d.width, d.height, g);
    g.drawRect(00, d.width - 1, d.height - 1);
  }

  public void drawCenteredString(String s, int w, int h, Graphics g) {
    FontMetrics fm = g.getFontMetrics();
    int x = (w - fm.stringWidth(s)) 2;
    int y = (fm.getAscent() (h - (fm.getAscent() + fm.getDescent())) 2);
    g.drawString(s, x, y);
  }
}














16.24.Font Metrics
16.24.1.Font Metrics: the wealth of dimensional data about a font
16.24.2.Font base line
16.24.3.Getting Char with based on current font
16.24.4.calls stringWidth (String) to center several text messagescalls stringWidth (String) to center several text messages
16.24.5.Center text.Center text.
16.24.6.Draw text to the leftDraw text to the left
16.24.7.Draw text to the rightDraw text to the right
16.24.8.Draw text to the centerDraw text to the center
16.24.9.Text justifyText justify
16.24.10.Draw font metrics
16.24.11.Display a text in 3 dimensions
16.24.12.Obtain FontMetrics of different fonts
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.