Java Graphics Draw Multiline String drawMultilineString(Graphics g, String s, int alignment, Rectangle r, boolean print)

Here you can find the source of drawMultilineString(Graphics g, String s, int alignment, Rectangle r, boolean print)

Description

Draws a multi line text and/or calculates the dimensions of the text when drawn into the given Graphics object.

License

Apache License

Parameter

Parameter Description
g Graphics context to paint into
s Text to draw
alignment Text alignment ( #LEFT / #CENTER / #RIGHT | #TOP / #MIDDLE / #BOTTOM )
r Rectangle containing the drawing region
print true Draws the text<br> false Calculates the text dimensions only If r.width &gt; 0 then the text lines are wrapped to this width.<br> If r.width is 0 or print is false, the method writes the width of the longest line back into r.width.<br> Note: The height of the text is always written back into r.height!

Declaration

public static void drawMultilineString(Graphics g, String s, int alignment, Rectangle r, boolean print) 

Method Source Code

//package com.java2s;
/*/*from w  w w  .  ja  v  a  2s. co m*/
 *   Copyright 2007 skynamics AG
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

import java.awt.FontMetrics;
import java.awt.Graphics;

import java.awt.Rectangle;

public class Main {
    /** Flag for {@link #drawMultilineString(Graphics, String, int, Rectangle, boolean)}: Indicates that the text should be centered. */
    public static final int CENTER = (1 << 1);
    /** Flag for {@link #drawMultilineString(Graphics, String, int, Rectangle, boolean)}: Indicates that the text should be right justified. */
    public static final int RIGHT = (1 << 2);
    /** Flag for {@link #drawMultilineString(Graphics, String, int, Rectangle, boolean)}: Indicates that the text should be displayed at the middle of the drawing area . */
    public static final int MIDDLE = (1 << 4);
    /** Flag for {@link #drawMultilineString(Graphics, String, int, Rectangle, boolean)}: Indicates that the text should be displayed at the bottom of the drawing area . */
    public static final int BOTTOM = (1 << 5);

    /**
     * Draws a multi line text and/or calculates the dimensions of the text
     * when drawn into the given Graphics object.
     *
     * @param g Graphics context to paint into
     * @param s Text to draw
     * @param alignment Text alignment ({@link #LEFT}/{@link #CENTER}/{@link #RIGHT} | {@link #TOP}/{@link #MIDDLE}/{@link #BOTTOM})
     * @param r Rectangle containing the drawing region
     * @param print
     *      true   Draws the text<br>
     *      false   Calculates the text dimensions only
     *
     * If r.width &gt; 0 then the text lines are wrapped to this width.<br>
     * If r.width is 0 or print is false, the method writes the width of the longest line back into r.width.<br>
     * Note: The height of the text is always written back into r.height!
     */
    public static void drawMultilineString(Graphics g, String s, int alignment, Rectangle r, boolean print) {
        drawMultilineString(g, null, s, alignment, r, print);
    }

    /**
     * Draws a multi line text and/or calculates the dimensions of the text
     * when drawn into the given Graphics object.
     *
     * @param g Graphics context to paint into (can be null if fm is supplied and print is false)
     * @param fm Font metrics of the current font or null to retrieve the metrics from the graphics context
     * @param s Text to draw
     * @param alignment Text alignment ({@link #LEFT}/{@link #CENTER}/{@link #RIGHT} | {@link #TOP}/{@link #MIDDLE}/{@link #BOTTOM})
     * @param r Rectangle containing the drawing region
     * @param print
     *      true   Draws the text<br>
     *      false   Calculates the text dimensions only
     *
     * If r.width &gt; 0 then the text lines are wrapped to this width.<br>
     * If r.width is 0 or print is false, the method writes the width of the longest line back into r.width.<br>
     * Note: The height of the text is always written back into r.height!
     */
    private static void drawMultilineString(Graphics g, FontMetrics fm, String s, int alignment, Rectangle r,
            boolean print) {
        if (s == null)
            return;

        String word = "";
        String line = "";
        int maxWidth = 0;
        int height = 0;
        boolean wordCompleted;
        boolean lineCompleted;
        int n = s.length();

        if (fm == null)
            fm = g.getFontMetrics();

        if (r.height != 0 && (alignment & (MIDDLE | BOTTOM)) != 0) {
            // we have a height specification for the drawing rectangle and we shall print
            // the text in the middle of the rectangle or at the bottom.
            // we need to now the vertical extent of the text, compute it.
            int totalHeight = 0;
            for (int i = 0; i < n; i++) {
                char c = s.charAt(i);

                if (c == '\n') {
                    wordCompleted = true;
                    lineCompleted = true;
                } else {
                    if (c == '\t') {
                        word += "        ";
                    } else {
                        word += c;
                    }
                    lineCompleted = (i == n - 1);
                    wordCompleted = lineCompleted || Character.isSpaceChar(c);
                }

                if (wordCompleted) {
                    if (r.width > 0) {
                        if (fm.stringWidth(line + word) > r.width) {
                            totalHeight += fm.getHeight();
                            line = word;
                        } else {
                            line += word;
                        }
                    } else {
                        line += word;
                    }

                    word = "";
                }

                if (lineCompleted) {
                    totalHeight += fm.getHeight();
                    line = "";
                }
            }

            // Compute the offset for the first line to print
            if ((alignment & MIDDLE) != 0) {
                height = (r.height - totalHeight) / 2;
            } else {
                height = r.height - totalHeight;
            }
        }

        for (int i = 0; i < n; i++) {
            char c = s.charAt(i);

            if (c == '\n') {
                wordCompleted = true;
                lineCompleted = true;
            } else {
                if (c == '\t') {
                    word += "        ";
                } else {
                    word += c;
                }
                lineCompleted = (i == n - 1);
                wordCompleted = lineCompleted || Character.isSpaceChar(c);
            }

            if (wordCompleted) {
                if (r.width > 0) {
                    if (fm.stringWidth(line + word) > r.width) {
                        if (fm.stringWidth(line) > maxWidth) {
                            maxWidth = fm.stringWidth(line);
                        }
                        height += fm.getHeight();

                        if (print) {
                            drawString(g, line, alignment,
                                    new Rectangle(r.x, r.y + height - fm.getDescent(), r.width, 0));
                        }
                        line = word;
                    } else {
                        line += word;
                    }
                } else {
                    line += word;
                }

                word = "";
            }

            if (lineCompleted) {
                if (fm.stringWidth(line) > maxWidth) {
                    maxWidth = fm.stringWidth(line);
                }
                height += fm.getHeight();

                if (print) {
                    drawString(g, line, alignment, new Rectangle(r.x, r.y + height - fm.getDescent(), r.width, 0));
                }

                line = "";
            }
        }

        if (r.width == 0 || !print) {
            r.width = maxWidth;
        }
        r.height = height;
    }

    /**
     * Draws a string into a Graphics object.
     *
     * @param g Graphics context to paint into
     * @param s Text to draw
     * @param alignment Text alignment ({@link #LEFT}/{@link #CENTER}/{@link #RIGHT})
     * @param r Bounding rectangle (width has to be greater 0 when the alignment is CENTER or RIGHT)
     */
    public static void drawString(Graphics g, String s, int alignment, Rectangle r) {
        if (s == null)
            return;

        int x = r.x;
        if ((alignment & CENTER) != 0) {
            // Center text in line
            x += (r.width - g.getFontMetrics().stringWidth(s)) / 2;
        } else if ((alignment & RIGHT) != 0) {
            // Right-align text
            x += r.width - g.getFontMetrics().stringWidth(s);
        }
        g.drawString(s, x, r.y);
    }
}

Related

  1. draw(String _str, Graphics2D _g2, int _nX0, int _nY0, int _nX1, int _nY1)
  2. drawMultilineText(final Graphics2D gc, final int x, int y, final String text)
  3. drawMultiLineText(String text, Graphics G, int x, int y)
  4. drawRightMultiLineText(String text, Graphics G, int x, int y)
  5. drawString(Graphics g, String s, int x, int y)