Draw text with TextLayout : Text Layout « 2D Graphics GUI « Java






Draw text with TextLayout

     

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

   
    
    
    
    
  








Related examples in the same category

1.JFreeChart: Draw String DemoJFreeChart: Draw String Demo
2.Unicode: test layoutUnicode: test layout
3.Unicode displayUnicode display
4.Line break for textlayoutLine break for textlayout
5.Mouse hit and textlayoutMouse hit and textlayout
6.TextLayout demoTextLayout demo
7.Draw text along a curveDraw text along a curve
8.TextHitInfo Demo: tell you which is the letter you are clickingTextHitInfo Demo: tell you which is the letter you are clicking
9.TextAttribute: Underline and strike throughTextAttribute: Underline and strike through
10.TextAttribute: color and fontTextAttribute: color and font
11.Hightlight text by drag and selectionHightlight text by drag and selection
12.LineMetrics: the metrics to layout characters along a lineLineMetrics: the metrics to layout characters along a line
13.Paragraph LayoutParagraph Layout
14.Caret actionCaret action
15.Caret and TextLayoutCaret and TextLayout
16.Another Line Break Demo
17.A display of text, formatted by us instead of by AWT/SwingA display of text, formatted by us instead of by AWT/Swing
18.Drawing a Paragraph of Text
19.Getting the Shape from the Outline of Text
20.Drawing Text with Mixed Styles
21.Drawing multi-line text with AttributedString and LineBreakMeasurer
22.Draws the string at the specified location underlining the specified character
23.Renders a paragraph of text (line breaks ignored) to an image (created and returned).