Styled Text : TextLayout « 2D Graphics « Java Tutorial






Styled Text
import java.awt.Canvas;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;

import javax.swing.JFrame;

public class Draw2DTextLayout extends JFrame {

  public static void main(String args[]) {
    Draw2DTextLayout app = new Draw2DTextLayout();
  }

  public Draw2DTextLayout() {
    add("Center", new MyCanvas());
    setSize(400, 400);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
  }

  class MyCanvas extends Canvas {
    public void paint(Graphics graphics) {
      Graphics2D g = (Graphics2D) graphics;
      FontRenderContext frc = g.getFontRenderContext();
      TextLayout[] s = new TextLayout[3];
      Font f1 = new Font("Helvetica", Font.BOLD, 24);
      Font f2 = new Font("TimesRoman", Font.ITALIC, 14);
      Font f3 = new Font("Helvetica", Font.PLAIN, 12);
      s[0] = new TextLayout("This is the first sentence.", f1, frc);
      s[1] = new TextLayout("This is the second sentence.", f2, frc);
      s[2] = new TextLayout("This is the third sentence.", f3, frc);

      int yOffset = 0;
      for (int i = 0; i < s.length; ++i) {
        s[i].draw(g, 100, 100 + yOffset);
        yOffset += s[i].getAscent() + s[i].getDescent() + s[i].getLeading();
      }
    }
  }
}








16.21.TextLayout
16.21.1.Styled TextStyled Text
16.21.2.Text Layout with mouse clicking and selecting actionText Layout with mouse clicking and selecting action
16.21.3.Draw text with TextLayout
16.21.4.Make your own animation from a series of images
16.21.5.Drawing a Paragraph of Text
16.21.6.Getting the Shape from the Outline of Text
16.21.7.Drawing Text with Mixed Styles
16.21.8.Line Break Measurer DemoLine Break Measurer Demo