Draw text with TextLayout : TextLayout « 2D Graphics « Java Tutorial






import java.awt.Color;
import java.awt.Dimension;
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.TextLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {
  public Main() {
    setBackground(Color.white);
  }

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

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

    g2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    FontRenderContext frc = g2D.getFontRenderContext();
    Font font1 = new Font("Courier", Font.BOLD, 24);
    String str1 = new String("Java");
    TextLayout tl = new TextLayout(str1, font1, frc);
    g2D.setColor(Color.gray);
    tl.draw(g2D, 50, 150);
  }

  public static void main(String s[]) {
    JFrame frame1 = new JFrame("2D Text");
    frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame1.getContentPane().add("Center", new Main());
    frame1.pack();
    frame1.setSize(new Dimension(500, 300));
    frame1.setVisible(true);
  }
}








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