Java Swing Font Metrics getTextBounds(FontMetrics fm, String s)

Here you can find the source of getTextBounds(FontMetrics fm, String s)

Description

Get bounds of a multi-line text

License

Open Source License

Parameter

Parameter Description
fm the font metrics
s the string

Return

the bounds

Declaration

public static Rectangle2D getTextBounds(FontMetrics fm, String s) 

Method Source Code


//package com.java2s;
//       Distributed under the GNU Lesser General Public License

import java.awt.geom.*;

import java.awt.*;

import javax.swing.*;

public class Main {
    /**//from  w w w  . jav a2  s  . c o m
     * Get bounds of a multi-line text
     * 
     * @param fm the font metrics
     * @param s the string
     * @return the bounds
     */
    public static Rectangle2D getTextBounds(FontMetrics fm, String s) {

        if (s.indexOf('\n') >= 0) {
            String[] a = s.split("\n");

            int fh = fm.getFont().getSize();
            int lh = (int) fh + 1;
            double h = lh * a.length;

            double w = 0;
            for (int ai = 0; ai < a.length; ai++) {
                int tw = SwingUtilities.computeStringWidth(fm, a[ai]);
                if (tw > w)
                    w = tw;
            }

            return new Rectangle2D.Double(0, 0, w, h);
        } else {

            int h = fm.getFont().getSize();
            int w = SwingUtilities.computeStringWidth(fm, s);

            return new Rectangle2D.Double(0, 0, w, h);
        }
    }

    /**
     * Get bounds of a multi-line text
     * 
     * @param g the graphics context
     * @param s the string
     * @return the bounds
     */
    public static Rectangle2D getTextBounds(Graphics g, String s) {

        FontMetrics fm = g.getFontMetrics();
        return getTextBounds(fm, s);
    }
}

Related

  1. getFRC(JComponent c, FontMetrics fm)
  2. getImage(String text, boolean clockwise, Font font, FontMetrics fm, Color bg, Color fontColor)
  3. getMethodGetFontMetrics()
  4. getTabbedTextOffset(Segment s, FontMetrics metrics, int x0, int x, TabExpander e, int startOffset)
  5. getTabbedTextWidth(Segment s, FontMetrics metrics, int x, TabExpander e, int startOffset)
  6. getWidthOfText(FontMetrics fontMetrics, String text)
  7. layoutMultilineCompoundLabel(JComponent c, FontMetrics fm, String text, Icon icon, int verticalAlignment, int horizontalAlignment, int verticalTextPosition, int horizontalTextPosition, Rectangle viewR, Rectangle iconR, Rectangle textR, int textIconGap, int minLines, int maxLines)
  8. stringWidth(JComponent c, FontMetrics fm, String string)
  9. wrapString(String s, FontMetrics fm, int width)