Draws a String at the given location, underlining the first occurrence of a specified character. - Java 2D Graphics

Java examples for 2D Graphics:Shape

Description

Draws a String at the given location, underlining the first occurrence of a specified character.

Demo Code

/* BasicGraphicsUtils.java
   Copyright (C) 2003 Free Software Foundation, Inc.

This file is part of GNU Classpath.//from  w  ww. j  a  v  a2s .co m

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */
//package com.java2s;

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;

import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;

public class Main {
    /**
     * Draws a String at the given location, underlining the first
     * occurrence of a specified character. The algorithm for determining
     * the underlined position is not sensitive to case. If the
     * character is not part of <code>text</code>, the text will be
     * drawn without underlining. Drawing is performed in the current
     * color and font of <code>g</code>.
     *
     * <p><img src="doc-files/BasicGraphicsUtils-5.png" width="500"
     * height="100" alt="[An illustration showing how to use the
     * method]" />
     *
     * @param g the graphics into which the String is drawn.
     *
     * @param text the String to draw.
     *
     * @param underlinedChar the character whose first occurrence in
     *        <code>text</code> will be underlined. It is not clear
     *        why the API specification declares this argument to be
     *        of type <code>int</code> instead of <code>char</code>.
     *        While this would allow to pass Unicode characters outside
     *        Basic Multilingual Plane 0 (U+0000 .. U+FFFE), at least
     *        the GNU Classpath implementation does not underline
     *        anything if <code>underlinedChar</code> is outside
     *        the range of <code>char</code>.
     *
     * @param x the x coordinate of the text, as it would be passed to
     *        {@link java.awt.Graphics#drawString(java.lang.String,
     *        int, int)}.
     *
     * @param y the y coordinate of the text, as it would be passed to
     *        {@link java.awt.Graphics#drawString(java.lang.String,
     *        int, int)}.
     */
    public static void drawString(Graphics g, String text,
            int underlinedChar, int x, int y) {
        int index = -1;

        /* It is intentional that lower case is used. In some languages,
         * the set of lowercase characters is larger than the set of
         * uppercase ones. Therefore, it is good practice to use lowercase
         * for such comparisons (which really means that the author of this
         * code can vaguely remember having read some Unicode techreport
         * with this recommendation, but is too lazy to look for the URL).
         */
        if ((underlinedChar >= 0) || (underlinedChar <= 0xffff))
            index = text.toLowerCase().indexOf(
                    Character.toLowerCase((char) underlinedChar));

        drawStringUnderlineCharAt(g, text, index, x, y);
    }

    /**
     * Draws a String at the given location, underlining the character
     * at the specified index. Drawing is performed in the current color
     * and font of <code>g</code>.
     *
     * <p><img src="doc-files/BasicGraphicsUtils-5.png" width="500"
     * height="100" alt="[An illustration showing how to use the
     * method]" />
     *
     * @param g the graphics into which the String is drawn.
     *
     * @param text the String to draw.
     *
     * @param underlinedIndex the index of the underlined character in
     *        <code>text</code>.  If <code>underlinedIndex</code> falls
     *        outside the range <code>[0, text.length() - 1]</code>, the
     *        text will be drawn without underlining anything.
     *
     * @param x the x coordinate of the text, as it would be passed to
     *        {@link java.awt.Graphics#drawString(java.lang.String,
     *        int, int)}.
     *
     * @param y the y coordinate of the text, as it would be passed to
     *        {@link java.awt.Graphics#drawString(java.lang.String,
     *        int, int)}.
     *
     * @since 1.4
     */
    public static void drawStringUnderlineCharAt(Graphics g, String text,
            int underlinedIndex, int x, int y) {
        Graphics2D g2;
        Rectangle2D.Double underline;
        FontRenderContext frc;
        FontMetrics fmet;
        LineMetrics lineMetrics;
        Font font;
        TextLayout layout;
        double underlineX1, underlineX2;
        boolean drawUnderline;
        int textLength;

        textLength = text.length();
        if (textLength == 0)
            return;

        drawUnderline = (underlinedIndex >= 0)
                && (underlinedIndex < textLength);

        if (!(g instanceof Graphics2D)) {
            /* Fall-back. This is likely to produce garbage for any text
             * containing right-to-left (Hebrew or Arabic) characters, even
             * if the underlined character is left-to-right.
             */
            g.drawString(text, x, y);
            if (drawUnderline) {
                fmet = g.getFontMetrics();
                g.fillRect(
                        /* x */x
                                + fmet.stringWidth(text.substring(0,
                                        underlinedIndex)),
                        /* y */y + fmet.getDescent() - 1,
                        /* width */fmet.charWidth(text
                                .charAt(underlinedIndex)),
                        /* height */1);
            }

            return;
        }

        g2 = (Graphics2D) g;
        font = g2.getFont();
        frc = g2.getFontRenderContext();
        lineMetrics = font.getLineMetrics(text, frc);
        layout = new TextLayout(text, font, frc);

        /* Draw the text. */
        layout.draw(g2, x, y);
        if (!drawUnderline)
            return;

        underlineX1 = x
                + layout.getLogicalHighlightShape(underlinedIndex,
                        underlinedIndex).getBounds2D().getX();
        underlineX2 = x
                + layout.getLogicalHighlightShape(underlinedIndex + 1,
                        underlinedIndex + 1).getBounds2D().getX();

        underline = new Rectangle2D.Double();
        if (underlineX1 < underlineX2) {
            underline.x = underlineX1;
            underline.width = underlineX2 - underlineX1;
        } else {
            underline.x = underlineX2;
            underline.width = underlineX1 - underlineX2;
        }

        underline.height = lineMetrics.getUnderlineThickness();
        underline.y = lineMetrics.getUnderlineOffset();
        if (underline.y == 0) {
            /* Some fonts do not specify an underline offset, although they
             * actually should do so. In that case, the result of calling
             * lineMetrics.getUnderlineOffset() will be zero. Since it would
             * look very ugly if the underline was be positioned immediately
             * below the baseline, we check for this and move the underline
             * below the descent, as shown in the following ASCII picture:
             *
             *   #####       ##### #
             *  #     #     #     #
             *  #     #     #     #
             *  #     #     #     #
             *   #####       ######        ---- baseline (0)
             *                    #
             *                    #
             * ------------------###----------- lineMetrics.getDescent()
             */
            underline.y = lineMetrics.getDescent();
        }

        underline.y += y;
        g2.fill(underline);
    }
}

Related Tutorials