Mega Code Archive

 
Categories / Java Tutorial / 2D Graphics
 

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