Draw text to the left : Font Metrics « 2D Graphics « Java Tutorial






Draw text to the left
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.util.StringTokenizer;

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

public class TextLayoutLeft extends JPanel {
  Dimension d;

  Font f = new Font("fontname", Font.PLAIN, 20);

  FontMetrics fm;

  int fh, ascent;

  int space;

  public static void main(String[] a) {
    JFrame f = new JFrame();
    f.setSize(300, 300);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(new TextLayoutLeft());
    f.setVisible(true);
  }
  public void paint(Graphics g) {
    d = getSize();
    g.setFont(f);
    if (fm == null) {
      fm = g.getFontMetrics();
      ascent = fm.getAscent();
      fh = ascent + fm.getDescent();
      space = fm.stringWidth(" ");
    }
    g.setColor(Color.black);
    StringTokenizer st = new StringTokenizer("this is a text. this is a test <BR> this is a text. this is a test");
    int x = 0;
    int nextx;
    int y = 0;
    String word, sp;
    int wordCount = 0;
    String line = "";
    while (st.hasMoreTokens()) {
      word = st.nextToken();
      if (word.equals("<BR>")) {
        drawString(g, line, wordCount, fm.stringWidth(line), y + ascent);
        line = "";
        wordCount = 0;
        x = 0;
        y = y + (fh * 2);
      } else {
        int w = fm.stringWidth(word);
        if ((nextx = (x + space + w)) > d.width) {
          drawString(g, line, wordCount, fm.stringWidth(line), y + ascent);
          line = "";
          wordCount = 0;
          x = 0;
          y = y + fh;
        }
        if (x != 0) {
          sp = " ";
        } else {
          sp = "";
        }
        line = line + sp + word;
        x = x + space + w;
        wordCount++;
      }
    }
    drawString(g, line, wordCount, fm.stringWidth(line), y + ascent);
  }

  public void drawString(Graphics g, String line, int wc, int lineW, int y) {
      g.drawString(line, 0, y);
  }
}








16.24.Font Metrics
16.24.1.Font Metrics: the wealth of dimensional data about a font
16.24.2.Font base line
16.24.3.Getting Char with based on current font
16.24.4.calls stringWidth (String) to center several text messagescalls stringWidth (String) to center several text messages
16.24.5.Center text.Center text.
16.24.6.Draw text to the leftDraw text to the left
16.24.7.Draw text to the rightDraw text to the right
16.24.8.Draw text to the centerDraw text to the center
16.24.9.Text justifyText justify
16.24.10.Draw font metrics
16.24.11.Display a text in 3 dimensions
16.24.12.Obtain FontMetrics of different fonts