Example usage for java.awt FontMetrics getStringBounds

List of usage examples for java.awt FontMetrics getStringBounds

Introduction

In this page you can find the example usage for java.awt FontMetrics getStringBounds.

Prototype

public Rectangle2D getStringBounds(String str, Graphics context) 

Source Link

Document

Returns the bounds of the specified String in the specified Graphics context.

Usage

From source file:Main.java

public static void main(String[] args) {
    String s = "The quick brown fox jumps over the lazy dog!";
    BufferedImage bi = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
    Graphics g = bi.getGraphics();
    FontMetrics fm = g.getFontMetrics();
    Rectangle2D b = fm.getStringBounds(s, g);
    System.out.println(b);//w w w. java2  s .c om
    bi = new BufferedImage((int) b.getWidth(), (int) (b.getHeight() + fm.getDescent()),
            BufferedImage.TYPE_INT_RGB);
    g = bi.getGraphics();
    g.drawString(s, 0, (int) b.getHeight());

    JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(bi)));

    // Technique 3 - JLabel
    JLabel l = new JLabel(s);
    l.setSize(l.getPreferredSize());
    bi = new BufferedImage(l.getWidth(), l.getHeight(), BufferedImage.TYPE_INT_RGB);
    g = bi.getGraphics();
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, 400, 100);
    l.paint(g);

    JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(bi)));
}

From source file:Main.java

public static void main(String args[]) {
    JFrame f = new JFrame();
    f.add(new JComponent() {
        public void paintComponent(Graphics g) {

            // Some parameters.
            String text = "Some Label";
            int centerX = 150, centerY = 100;
            int ovalWidth = 200, ovalHeight = 100;

            // Draw oval
            g.setColor(Color.BLUE);
            g.fillOval(centerX - ovalWidth / 2, centerY - ovalHeight / 2, ovalWidth, ovalHeight);

            // Draw centered text
            FontMetrics fm = g.getFontMetrics();
            double textWidth = fm.getStringBounds(text, g).getWidth();
            g.setColor(Color.WHITE);
            g.drawString(text, (int) (centerX - textWidth / 2), (int) (centerY + fm.getMaxAscent() / 2));

        }//from   w  w w. j a  v a 2s  . c  o  m
    });

    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(300, 300);
    f.setVisible(true);
}

From source file:Main.java

public static int getStringWidth(Graphics g, Font font, String text) {

    FontMetrics fm = g.getFontMetrics(font);
    return (int) fm.getStringBounds(text, g).getWidth();
}

From source file:Main.java

public static void drawCenteredString(Graphics g, String str, int x, int y) {
    FontMetrics metrics = g.getFontMetrics(g.getFont());
    Rectangle2D rect = metrics.getStringBounds(str, g);
    int w = (int) (rect.getWidth());
    int h = (int) (rect.getHeight());
    g.drawString(str, x - w / 2, y + h / 2);
}

From source file:Main.java

/**
 * computes the width of a string drawn on a canvas
 *
 * @param g the graphics object where to draw
 * @param f the font used to draw/* w  w  w.  j a  v  a  2s. c  om*/
 * @param strValue the string to draw
 * @return
 */
public static int getStringWidth(Graphics g, Font f, String strValue) {

    // gets the metrics of the font
    FontMetrics fm = g.getFontMetrics(f);

    // and returns its width
    return (int) fm.getStringBounds(strValue, g).getWidth();
}

From source file:Main.java

public static Rectangle calculateBoundsForComponent(JComponent comp, String text, int xOffset, int yOffset) {

    FontMetrics fm = comp.getFontMetrics(comp.getFont());
    Rectangle2D bounds = fm.getStringBounds(text, comp.getGraphics());

    return new Rectangle(xOffset + (int) bounds.getX(), yOffset,
            (int) Math.ceil(bounds.getWidth()) + (PADDING * 2),
            (int) Math.ceil(bounds.getHeight() + fm.getDescent()) + (PADDING * 2));
}

From source file:Main.java

public static int getStringHeight(Graphics g, Font font, String text) {

    if (font == null || g == null || text == null) {
        return -1;
    }//from   www.  j  av a2s  . c om

    FontMetrics fm = g.getFontMetrics(font);

    if (!text.contains(("\\n"))) {
        return (int) fm.getStringBounds(text, g).getHeight();
    }

    return Arrays.stream(text.split("\\\\n")).mapToInt(row -> (int) fm.getStringBounds(text, g).getHeight())
            .reduce(Integer::sum).getAsInt();
}

From source file:Main.java

public static void setJButtonSizesTheSame(final JButton[] btns) {
    if (btns == null) {
        throw new IllegalArgumentException();
    }//from   w ww .ja v a2 s. c  o m

    final Dimension maxSize = new Dimension(0, 0);
    for (int i = 0; i < btns.length; ++i) {
        final JButton btn = btns[i];
        final FontMetrics fm = btn.getFontMetrics(btn.getFont());
        final Rectangle2D bounds = fm.getStringBounds(btn.getText(), btn.getGraphics());
        final int boundsHeight = (int) bounds.getHeight();
        final int boundsWidth = (int) bounds.getWidth();
        maxSize.width = boundsWidth > maxSize.width ? boundsWidth : maxSize.width;
        maxSize.height = boundsHeight > maxSize.height ? boundsHeight : maxSize.height;
    }

    final Insets insets = btns[0].getInsets();
    maxSize.width += insets.left + insets.right;
    maxSize.height += insets.top + insets.bottom;

    for (int i = 0; i < btns.length; ++i) {
        final JButton btn = btns[i];
        btn.setPreferredSize(maxSize);
    }

    initComponentHeight(btns);
}

From source file:GUIUtils.java

/**
 * Change the sizes of all the passed buttons to be the size of the largest
 * one./*from   w ww  . j a  v a  2 s  .  c o m*/
 * 
 * @param btns
 *          Array of buttons to eb resized.
 * 
 * @throws IllegalArgumentException
 *           If <TT>btns</TT> is <TT>null</TT>.
 */
public static void setJButtonSizesTheSame(JButton[] btns) {
    if (btns == null) {
        throw new IllegalArgumentException("null JButton[] passed");
    }

    // Get the largest width and height
    final Dimension maxSize = new Dimension(0, 0);
    for (int i = 0; i < btns.length; ++i) {
        final JButton btn = btns[i];
        final FontMetrics fm = btn.getFontMetrics(btn.getFont());
        Rectangle2D bounds = fm.getStringBounds(btn.getText(), btn.getGraphics());
        int boundsHeight = (int) bounds.getHeight();
        int boundsWidth = (int) bounds.getWidth();
        maxSize.width = boundsWidth > maxSize.width ? boundsWidth : maxSize.width;
        maxSize.height = boundsHeight > maxSize.height ? boundsHeight : maxSize.height;
    }

    Insets insets = btns[0].getInsets();
    maxSize.width += insets.left + insets.right;
    maxSize.height += insets.top + insets.bottom;

    for (int i = 0; i < btns.length; ++i) {
        JButton btn = btns[i];
        btn.setPreferredSize(maxSize);
    }
}

From source file:Main.java

public static BufferedImage createRotatedTextImage(String text, int angle, Font ft) {
    Graphics2D g2d = null;//from  www.java 2  s.c o  m
    try {
        if (text == null || text.trim().length() == 0) {
            return null;
        }

        BufferedImage stringImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);

        g2d = (Graphics2D) stringImage.getGraphics();
        g2d.setFont(ft);

        FontMetrics fm = g2d.getFontMetrics();
        Rectangle2D bounds = fm.getStringBounds(text, g2d);

        TextLayout tl = new TextLayout(text, ft, g2d.getFontRenderContext());

        g2d.dispose();
        g2d = null;

        return createRotatedImage(tl, (int) bounds.getWidth(), (int) bounds.getHeight(), angle);
    } catch (Exception e) {
        e.printStackTrace();

        if (g2d != null) {
            g2d.dispose();
        }
    }

    return null;
}