Java/2D Graphics GUI

Материал из Java эксперт
Перейти к: навигация, поиск

A cache of the dynamically loaded fonts found in the fonts directory

    
/*
 * @(#)DemoFonts.java 1.17 06/08/29
 * 
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 * 
 * -Redistribution in binary form must reproduce the above copyright notice, 
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 * 
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may 
 * be used to endorse or promote products derived from this software without 
 * specific prior written permission.
 * 
 * This software is provided "AS IS," without a warranty of any kind. ALL 
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST 
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, 
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY 
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, 
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 * 
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
/*
 * @(#)DemoFonts.java 1.17 06/08/29
 */
import java.awt.Font;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
 * A cache of the dynamically loaded fonts found in the fonts directory.
 */
public class DemoFonts {
  // Prepare a static "cache" mapping font names to Font objects.
  private static String[] names = { "A.ttf" };
  private static Map<String, Font> cache = new ConcurrentHashMap<String, Font>(names.length);
  static {
    for (String name : names) {
      cache.put(name, getFont(name));
    }
  }
  public static Font getFont(String name) {
    Font font = null;
    if (cache != null) {
      if ((font = cache.get(name)) != null) {
        return font;
      }
    }
    String fName = "/fonts/" + name;
    try {
      InputStream is = DemoFonts.class.getResourceAsStream(fName);
      font = Font.createFont(Font.TRUETYPE_FONT, is);
    } catch (Exception ex) {
      ex.printStackTrace();
      System.err.println(fName + " not loaded.  Using serif font.");
      font = new Font("serif", Font.PLAIN, 24);
    }
    return font;
  }
}



Create font from true type font

  
import java.awt.Font;
import java.io.File;
import java.io.FileInputStream;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main {
  public static void main(String[] args) throws Exception {
    File f = new File("your.ttf");
    FileInputStream in = new FileInputStream(f);
    Font dynamicFont = Font.createFont(Font.TRUETYPE_FONT, in);
    Font dynamicFont32Pt = dynamicFont.deriveFont(32f);
    JLabel testLabel = new JLabel(dynamicFont.getName());
    testLabel.setFont(dynamicFont32Pt);
    JFrame frame = new JFrame("Font Loading Demo");
    frame.getContentPane().add(testLabel);
    frame.pack();
    frame.setVisible(true);
  }
}



Display font in a grid

  
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
  public static void main(String[] args) {
    final int columnCount = 10;
    final int side = 25;
    final int[][] grid = new int[50][columnCount];
    JPanel panel = new JPanel() {
      public void paintComponent(Graphics g) {
        Font font = new Font("WingDings", Font.PLAIN, 14);
        g.setFont(font);
        int off = 0;
        for (int i = 0; i < 256 * 256; i++) {
          if (font.canDisplay((char) i) == false) {
            continue;
          }
          off++;
          grid[off / columnCount][off % columnCount] = i;
          int x = off % columnCount * side;
          int y = (off / columnCount) * side + side;
          g.drawString(Character.toString((char)i), x, y);
        }
      }
    };
    JFrame frame = new JFrame();
    panel.setSize(300, 300);
    frame.getContentPane().add(panel);
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
}



Draw font inside a Rectangle

    
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class StringRectPaintPanel extends JPanel {
  public void paint(Graphics g) {
    g.setFont(new Font("",0,100));
    FontMetrics fm = getFontMetrics(new Font("",0,100));
    String s = "jexp";
    int x = 5;
    int y = 5;
    
    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);
      int h = fm.getHeight();
      int w = fm.charWidth(c);
      g.drawRect(x, y, w, h);
      g.drawString(String.valueOf(c), x, y + h);
      x = x + w;
    }
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(new StringRectPaintPanel());
    frame.setSize(500, 300);
    frame.setVisible(true);
  }
}



Finds and displays available fonts

   
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
/**
 * Finds and displays available fonts
 * <p>
 * TODO: should be a JTable with the text name in one column and the demo in a
 * JLabel in the other.
 * 
 * @author Ian Darwin (original)
 */
public class FontDemo extends JComponent {
  /** The list of Fonts */
  protected String[] fontNames;
  /** The fonts themselves */
  protected Font[] fonts;
  /** How much space between each name */
  static final int YINCR = 20;
  /**
   * Construct a FontDemo -- Sets title and gets array of fonts on the system
   */
  public FontDemo() {
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    // For JDK 1.1: returns about 10 names (Serif, SansSerif, etc.)
    // fontNames = toolkit.getFontList();
    // For JDK 1.2: a much longer list; most of the names that come
    // with your OS (e.g., Arial, Lucida, Lucida Bright, Lucida Sans...)
    fontNames = GraphicsEnvironment.getLocalGraphicsEnvironment()
        .getAvailableFontFamilyNames();
    fonts = new Font[fontNames.length];
  }
  public Dimension getPreferredSize() {
    return new Dimension(500, fontNames.length * YINCR);
  }
  /**
   * Draws the font names in its font. Called by AWT when painting is needed
   * Does lazy evaluation of Font creation, caching the results (without this,
   * scrolling performance suffers even on a P3-750).
   */
  public void paint(Graphics g) {
    for (int i = 0; i < fontNames.length; i += 1) {
      if (fonts[i] == null) {
        fonts[i] = new Font(fontNames[i], Font.BOLD, 14);
      }
      g.setFont(fonts[i]);
      int x = 20;
      int y = 20 + (YINCR * i);
      g.drawString(fontNames[i], x, y);
    }
  }
  /** Simple main program to start it running */
  public static void main(String[] args) {
    JFrame f = new JFrame("Font Demo");
    f.getContentPane().add(new JScrollPane(new FontDemo()));
    f.setSize(600, 700);
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
}



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



FontDemo lists the system fonts and provides a sample of each one(Have some problems)

   
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
////
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.Label;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/** FontDemo lists the system fonts and provides a sample of each one */
public class FontDemoLabel extends JFrame {
  String fl[];
  JPanel p;
  public FontDemoLabel() {
    super("Font Demo - Label");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container cp = getContentPane();
    // get font name list
    fl = GraphicsEnvironment.getLocalGraphicsEnvironment()
        .getAvailableFontFamilyNames();
    // IGNORE the setLayout and North/South stuff...
    // we will discuss it in a few pages!
    cp.setLayout(new BorderLayout());
    cp.add(BorderLayout.NORTH, new Label("Number of Fonts = " + fl.length,
        Label.CENTER));
    cp.add(BorderLayout.CENTER, p = new JPanel());
    p.setLayout(new GridLayout(5, 0, 5, 5));
    for (int i = 0; i < fl.length; i++) {
      JLabel lab;
      // The crux of the matter: for each font name,
      // create a label using the name as the text,
      // AND set the font to be the named font!
      p.add(lab = new JLabel(fl[i]));
      lab.setFont(new Font(fl[i], Font.ITALIC | Font.BOLD, 14));
    }
    pack();
  }
  public static void main(String[] av) {
    new FontDemoLabel().setVisible(true);
  }
}



Font Derivation

   
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.TextAttribute;
import java.awt.geom.AffineTransform;
import java.util.Hashtable;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class FontDerivation extends JPanel {
  public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
    // Create a 1-point font.
    Font font = new Font("Serif", Font.PLAIN, 1);
    float x = 20, y = 20;
    Font font24 = font.deriveFont(24.0f);
    g2.setFont(font24);
    g2.drawString("font.deriveFont(24.0f)", x, y += 30);
    Font font24italic = font24.deriveFont(Font.ITALIC);
    g2.setFont(font24italic);
    g2.drawString("font24.deriveFont(Font.ITALIC)", x, y += 30);
    AffineTransform at = new AffineTransform();
    at.shear(.2, 0);
    Font font24shear = font24.deriveFont(at);
    g2.setFont(font24shear);
    g2.drawString("font24.deriveFont(at)", x, y += 30);
    Hashtable attributes = new Hashtable();
    attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD);
    Font font24bold = font24.deriveFont(attributes);
    g2.setFont(font24bold);
    g2.drawString("font24.deriveFont(attributes)", x, y += 30);
  }
  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.getContentPane().add(new FontDerivation());
    f.setSize(350, 250);
    f.show();
  }
}



Font List

   
/*
 * Copyright (c) 2000 David Flanagan.  All rights reserved.
 * This code is from the book Java Examples in a Nutshell, 2nd Edition.
 * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
 * You may study, use, and modify it for any non-commercial purpose.
 * You may distribute it non-commercially as long as you retain this notice.
 * For a commercial use license, or to purchase the book (recommended),
 * visit http://www.davidflanagan.ru/javaexamples2.
 */
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
 * An applet that displays the standard fonts and styles available in Java 1.1
 */
public class FontList extends JPanel {
  // The available font families
  String[] families = { "Serif", // "TimesRoman" in Java 1.0
      "SansSerif", // "Helvetica" in Java 1.0
      "Monospaced" }; // "Courier" in Java 1.0
  // The available font styles and names for each one
  int[] styles = { Font.PLAIN, Font.ITALIC, Font.BOLD,
      Font.ITALIC + Font.BOLD };
  String[] stylenames = { "Plain", "Italic", "Bold", "Bold Italic" };
  // Draw the applet.
  public void paint(Graphics g) {
    for (int f = 0; f < families.length; f++) { // for each family
      for (int s = 0; s < styles.length; s++) { // for each style
        Font font = new Font(families[f], styles[s], 18); // create font
        g.setFont(font); // set font
        String name = families[f] + " " + stylenames[s]; // create name
        g.drawString(name, 20, (f * 4 + s + 1) * 20); // display name
      }
    }
  }
  public static void main(String[] a) {
    JFrame f = new JFrame();
    f.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    f.setContentPane(new FontList());
    f.setSize(300,300);
    f.setVisible(true);
  }
}



Font paint

   
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SimpleFont extends JPanel{
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
        
        String s = "Java Source and Support";
        Font font = new Font("Serif", Font.PLAIN, 24);
        FontRenderContext frc = g2.getFontRenderContext();
        GlyphVector gv = font.createGlyphVector(frc, s);
        g2.drawGlyphVector(gv, 40, 60);
      }
  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.getContentPane().add(new SimpleFont());
    f.setSize(350, 250);
    f.show();
  }
}



Load font from ttf file

    
/*
 * @(#)DemoFonts.java 1.17 06/08/29
 * 
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 * 
 * -Redistribution in binary form must reproduce the above copyright notice, 
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 * 
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may 
 * be used to endorse or promote products derived from this software without 
 * specific prior written permission.
 * 
 * This software is provided "AS IS," without a warranty of any kind. ALL 
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST 
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, 
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY 
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, 
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 * 
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
/*
 * @(#)DemoFonts.java 1.17 06/08/29
 */
import java.awt.Font;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
 * A cache of the dynamically loaded fonts found in the fonts directory.
 */
public class DemoFonts {
  // Prepare a static "cache" mapping font names to Font objects.
  private static String[] names = { "A.ttf" };
  private static Map<String, Font> cache = new ConcurrentHashMap<String, Font>(names.length);
  static {
    for (String name : names) {
      cache.put(name, getFont(name));
    }
  }
  public static Font getFont(String name) {
    Font font = null;
    if (cache != null) {
      if ((font = cache.get(name)) != null) {
        return font;
      }
    }
    String fName = "/fonts/" + name;
    try {
      InputStream is = DemoFonts.class.getResourceAsStream(fName);
      font = Font.createFont(Font.TRUETYPE_FONT, is);
    } catch (Exception ex) {
      ex.printStackTrace();
      System.err.println(fName + " not loaded.  Using serif font.");
      font = new Font("serif", Font.PLAIN, 24);
    }
    return font;
  }
}



Obtain FontMetrics of different fonts

   
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class Main extends JFrame {
  public Main() {
    super("Demonstrating FontMetrics");
    setSize(510, 210);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
  public void paint(Graphics g) {
    g.setFont(new Font("SansSerif", Font.BOLD, 12));
    FontMetrics fm = g.getFontMetrics();
    g.drawString("Current font: " + g.getFont(), 10, 40);
    g.drawString("Ascent: " + fm.getAscent(), 10, 55);
    g.drawString("Descent: " + fm.getDescent(), 10, 70);
    g.drawString("Height: " + fm.getHeight(), 10, 85);
    g.drawString("Leading: " + fm.getLeading(), 10, 100);
    Font font = new Font("Serif", Font.ITALIC, 14);
    fm = g.getFontMetrics(font);
    g.setFont(font);
    g.drawString("Current font: " + font, 10, 130);
    g.drawString("Ascent: " + fm.getAscent(), 10, 145);
    g.drawString("Descent: " + fm.getDescent(), 10, 160);
    g.drawString("Height: " + fm.getHeight(), 10, 175);
    g.drawString("Leading: " + fm.getLeading(), 10, 190);
  }
  public static void main(String args[]) {
    Main app = new Main();
  }
}



Outline Font paint

   
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.net.URL;
import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class FontPaint extends JApplet {
  public void init() {
    FontPanel fontPanel = new FontPanel();
    getContentPane().add(fontPanel, BorderLayout.CENTER);
  }
  public static void main(String[] args) {
    FontPanel starPanel = new FontPanel();
    JFrame f = new JFrame("Font");
    f.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    f.getContentPane().add(starPanel, BorderLayout.CENTER);
    f.setSize(new Dimension(550, 200));
    f.setVisible(true);
  }
}
class FontPanel extends JPanel {
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    setBackground(Color.white);
    int width = getSize().width;
    int height = getSize().height;
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_RENDERING,
        RenderingHints.VALUE_RENDER_QUALITY);
    FontRenderContext frc = g2.getFontRenderContext();
    Font f = new Font("Helvetica", 1, 60);
    String s = new String("Java Source and Support.");
    TextLayout textTl = new TextLayout(s, f, frc);
    AffineTransform transform = new AffineTransform();
    Shape outline = textTl.getOutline(null);
    Rectangle outlineBounds = outline.getBounds();
    transform = g2.getTransform();
    transform.translate(width / 2 - (outlineBounds.width / 2), height / 2
        + (outlineBounds.height / 2));
    g2.transform(transform);
    g2.setColor(Color.blue);
    g2.draw(outline);
    g2.setClip(outline);
  }
}



Wrap string according to FontMetrics

   
import java.awt.FontMetrics;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/**
 * Globally available utility classes, mostly for string manipulation.
 * 
 * @author Jim Menard, 
 */
public class StringUtils {
  /**
   * Returns an array of strings, one for each line in the string after it has
   * been wrapped to fit lines of <var>maxWidth</var>. Lines end with any of
   * cr, lf, or cr lf. A line ending at the end of the string will not output a
   * further, empty string.
   * <p>
   * This code assumes <var>str</var> is not <code>null</code>.
   * 
   * @param str
   *          the string to split
   * @param fm
   *          needed for string width calculations
   * @param maxWidth
   *          the max line width, in points
   * @return a non-empty list of strings
   */
  public static List wrap(String str, FontMetrics fm, int maxWidth) {
    List lines = splitIntoLines(str);
    if (lines.size() == 0)
      return lines;
    ArrayList strings = new ArrayList();
    for (Iterator iter = lines.iterator(); iter.hasNext();)
      wrapLineInto((String) iter.next(), strings, fm, maxWidth);
    return strings;
  }
  /**
   * Given a line of text and font metrics information, wrap the line and add
   * the new line(s) to <var>list</var>.
   * 
   * @param line
   *          a line of text
   * @param list
   *          an output list of strings
   * @param fm
   *          font metrics
   * @param maxWidth
   *          maximum width of the line(s)
   */
  public static void wrapLineInto(String line, List list, FontMetrics fm, int maxWidth) {
    int len = line.length();
    int width;
    while (len > 0 && (width = fm.stringWidth(line)) > maxWidth) {
      // Guess where to split the line. Look for the next space before
      // or after the guess.
      int guess = len * maxWidth / width;
      String before = line.substring(0, guess).trim();
      width = fm.stringWidth(before);
      int pos;
      if (width > maxWidth) // Too long
        pos = findBreakBefore(line, guess);
      else { // Too short or possibly just right
        pos = findBreakAfter(line, guess);
        if (pos != -1) { // Make sure this doesn"t make us too long
          before = line.substring(0, pos).trim();
          if (fm.stringWidth(before) > maxWidth)
            pos = findBreakBefore(line, guess);
        }
      }
      if (pos == -1)
        pos = guess; // Split in the middle of the word
      list.add(line.substring(0, pos).trim());
      line = line.substring(pos).trim();
      len = line.length();
    }
    if (len > 0)
      list.add(line);
  }
  /**
   * Returns the index of the first whitespace character or "-" in <var>line</var>
   * that is at or before <var>start</var>. Returns -1 if no such character is
   * found.
   * 
   * @param line
   *          a string
   * @param start
   *          where to star looking
   */
  public static int findBreakBefore(String line, int start) {
    for (int i = start; i >= 0; --i) {
      char c = line.charAt(i);
      if (Character.isWhitespace(c) || c == "-")
        return i;
    }
    return -1;
  }
  /**
   * Returns the index of the first whitespace character or "-" in <var>line</var>
   * that is at or after <var>start</var>. Returns -1 if no such character is
   * found.
   * 
   * @param line
   *          a string
   * @param start
   *          where to star looking
   */
  public static int findBreakAfter(String line, int start) {
    int len = line.length();
    for (int i = start; i < len; ++i) {
      char c = line.charAt(i);
      if (Character.isWhitespace(c) || c == "-")
        return i;
    }
    return -1;
  }
  /**
   * Returns an array of strings, one for each line in the string. Lines end
   * with any of cr, lf, or cr lf. A line ending at the end of the string will
   * not output a further, empty string.
   * <p>
   * This code assumes <var>str</var> is not <code>null</code>.
   * 
   * @param str
   *          the string to split
   * @return a non-empty list of strings
   */
  public static List splitIntoLines(String str) {
    ArrayList strings = new ArrayList();
    int len = str.length();
    if (len == 0) {
      strings.add("");
      return strings;
    }
    int lineStart = 0;
    for (int i = 0; i < len; ++i) {
      char c = str.charAt(i);
      if (c == "\r") {
        int newlineLength = 1;
        if ((i + 1) < len && str.charAt(i + 1) == "\n")
          newlineLength = 2;
        strings.add(str.substring(lineStart, i));
        lineStart = i + newlineLength;
        if (newlineLength == 2) // skip \n next time through loop
          ++i;
      } else if (c == "\n") {
        strings.add(str.substring(lineStart, i));
        lineStart = i + 1;
      }
    }
    if (lineStart < len)
      strings.add(str.substring(lineStart));
    return strings;
  }
}