full justification with a java graphics drawstring replacement - Java 2D Graphics

Java examples for 2D Graphics:Print

Description

full justification with a java graphics drawstring replacement

Demo Code


//package com.java2s;

import java.awt.Graphics;

public class Main {
    /**//  w ww.ja  v a2 s .  c  om
     * From: http://stackoverflow.com/questions/400566/full-justification-with-a-java-graphics-drawstring-replacement
     * Edited to include parameter for extra height between lines.
     * @author coobird (StackOverflow.com)
     * @param g
     * @param s
     * @param x
     * @param y
     * @param width
     */
    private static void drawString(Graphics g, String s, int x, int y,
            int width, int extraHeight) {
        // FontMetrics gives us information about the width,
        // height, etc. of the current Graphics object's Font.
        java.awt.FontMetrics fm = g.getFontMetrics();

        int lineHeight = fm.getHeight() + extraHeight;

        int curX = x;
        int curY = y;

        String[] words = s.split(" ");

        for (String word : words) {
            // Find out thw width of the word.
            int wordWidth = fm.stringWidth(word + " ");

            // If text exceeds the width, then move to next line.
            if (curX + wordWidth >= x + width) {
                curY += lineHeight;
                curX = x;
            }

            g.drawString(word, curX, curY);

            // Move over to the right for next word.
            curX += wordWidth;
        }
    }
}

Related Tutorials