Example usage for java.awt Graphics getFontMetrics

List of usage examples for java.awt Graphics getFontMetrics

Introduction

In this page you can find the example usage for java.awt Graphics getFontMetrics.

Prototype

public FontMetrics getFontMetrics() 

Source Link

Document

Gets the font metrics of the current font.

Usage

From source file:Main.java

public static void setLabelCenter(JLabel label, String str, int width, int height) {
    Graphics g = label.getGraphics();
    Color c = g.getColor();//from w  ww.  j a v  a2s  .  c  o m
    g.setColor(Color.BLUE);
    label.setText(str);
    int strWidth = SwingUtilities.computeStringWidth(g.getFontMetrics(), str);
    int lX = width / 2 - strWidth;
    int lY = g.getFont().getSize() / 2;
    //System.out.printf("\"label\"+%s X:%d,Y:%d\n",str,lX,lY);
    label.setBounds(lX, lY, strWidth, g.getFont().getSize());
    g.setColor(c);
}

From source file:Main.java

public static Rectangle getTextRectangle(JLabel label) {

    String text = label.getText();
    Icon icon = (label.isEnabled()) ? label.getIcon() : label.getDisabledIcon();

    if ((icon == null) && (text == null)) {
        return null;
    }//w ww .  java2 s.c  om

    Rectangle paintIconR = new Rectangle();
    Rectangle paintTextR = new Rectangle();
    Rectangle paintViewR = new Rectangle();
    Insets paintViewInsets = new Insets(0, 0, 0, 0);

    paintViewInsets = label.getInsets(paintViewInsets);
    paintViewR.x = paintViewInsets.left;
    paintViewR.y = paintViewInsets.top;
    paintViewR.width = label.getWidth() - (paintViewInsets.left + paintViewInsets.right);
    paintViewR.height = label.getHeight() - (paintViewInsets.top + paintViewInsets.bottom);

    Graphics g = label.getGraphics();
    if (g == null) {
        return null;
    }
    String clippedText = SwingUtilities.layoutCompoundLabel(label, g.getFontMetrics(), text, icon,
            label.getVerticalAlignment(), label.getHorizontalAlignment(), label.getVerticalTextPosition(),
            label.getHorizontalTextPosition(), paintViewR, paintIconR, paintTextR, label.getIconTextGap());

    return paintTextR;
}

From source file:GraphicsUtil.java

static public Rectangle getTextBounds(Graphics g, String text, int x, int y, int halign, int valign) {
    if (g == null)
        return new Rectangle(x, y, 0, 0);
    FontMetrics mets = g.getFontMetrics();
    int width = mets.stringWidth(text);
    int ascent = mets.getAscent();
    int height = ascent + mets.getDescent();
    Rectangle ret = new Rectangle(x, y, width, height);

    switch (halign) {
    case H_CENTER:
        ret.translate(-(width / 2), 0);// w w w  . ja v a  2  s.c  o m
        break;
    case H_RIGHT:
        ret.translate(-width, 0);
        break;
    default:
        ;
    }
    switch (valign) {
    case V_TOP:
        break;
    case V_CENTER:
        ret.translate(0, -(ascent / 2));
        break;
    case V_BASELINE:
        ret.translate(0, -ascent);
        break;
    case V_BOTTOM:
        ret.translate(0, -height);
        break;
    default:
        ;
    }
    return ret;
}

From source file:GraphicsUtil.java

static public void drawText(Graphics g, String text, int x, int y, int halign, int valign) {
    if (text.length() == 0)
        return;/*from w w  w .  ja  v a 2  s  .  c  o m*/
    Rectangle bd = getTextBounds(g, text, x, y, halign, valign);
    g.drawString(text, bd.x, bd.y + g.getFontMetrics().getAscent());
}

From source file:PaintUtils.java

/**
 * Returns the bounds that the text of a label will be drawn into.
 * Takes into account the current font metrics.
 *//*from w w  w.  ja va 2 s .  co m*/
public static Rectangle getTextBounds(Graphics g, JLabel label) {
    FontMetrics fm = g.getFontMetrics();
    Rectangle2D r2d = fm.getStringBounds(label.getText(), g);
    Rectangle rect = r2d.getBounds();
    int xOffset = 0;
    switch (label.getHorizontalAlignment()) {
    case SwingConstants.RIGHT:
    case SwingConstants.TRAILING:
        xOffset = label.getBounds().width - rect.width;
        break;
    case SwingConstants.CENTER:
        xOffset = (label.getBounds().width - rect.width) / 2;
        break;
    default:
    case SwingConstants.LEFT:
    case SwingConstants.LEADING:
        xOffset = 0;
        break;
    }
    int yOffset = 0;
    switch (label.getVerticalAlignment()) {
    case SwingConstants.TOP:
        yOffset = 0;
        break;
    case SwingConstants.CENTER:
        yOffset = (label.getBounds().height - rect.height) / 2;
        break;
    case SwingConstants.BOTTOM:
        yOffset = label.getBounds().height - rect.height;
        break;
    }
    return new Rectangle(xOffset, yOffset, rect.width, rect.height);
}

From source file:FontAlgo.java

private static TextualChar getTextualChar(char a_char) throws Throwable {
    BufferedImage bImg = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
    Graphics g = bImg.getGraphics();
    g.setColor(Color.green);// w ww.ja v a 2  s.c om
    g.fillRect(0, 0, WIDTH, HEIGHT);

    g.setFont(appliedFont);
    g.setColor(Color.black);
    g.drawString(new String(new char[] { a_char }), 10, g.getFontMetrics().getHeight());
    PixelGrabber p = new PixelGrabber(bImg, 0, 0, WIDTH, HEIGHT, true);

    if (p.grabPixels()) {
        char[][] pattern = new char[WIDTH][HEIGHT];
        int baseColourPixel = 0, contrastColourPixel = 0, x1 = 0, x2 = 0, y1 = 0, y2 = 0;
        int[] pixels = (int[]) p.getPixels();
        baseColourPixel = pixels[0];
        // System.out.println("base: " + base);
        int xCounter = 0, yCounter = 0;
        for (int iPixel : pixels) {
            // System.out.println(iX + " - " + iY);
            if (isReverse) {
                pattern[xCounter][yCounter] = iPixel == baseColourPixel ? CHAR_TO_PATTERN : ' ';
            } else {
                pattern[xCounter][yCounter] = iPixel != baseColourPixel ? CHAR_TO_PATTERN : ' ';
            }

            yCounter++;
            if (yCounter > 49) {
                xCounter++;
                yCounter = 0;
            }

            if (contrastColourPixel == 0 && iPixel != baseColourPixel) {
                contrastColourPixel = iPixel;
                x1 = xCounter - 2;
                y1 = yCounter - 3;
                y2 = yCounter + 3;
            }

            if (contrastColourPixel == iPixel) {
                x2 = xCounter + 3;

                if (y1 > (yCounter - 3)) {
                    y1 = yCounter - 3;
                }

                if (y2 < (yCounter + 3)) {
                    y2 = yCounter + 3;
                }
            }
        }
        return new TextualChar(x1, x2, y1, y2, pattern);
    }
    return null;
}

From source file:Main.java

/**
 * Paints string with underlined character at the specified index.
 *
 * @param g               graphics context
 * @param text            painted text/* w  w  w  .j  a  v  a 2  s  . co m*/
 * @param underlinedIndex underlined character index
 * @param x               text X coordinate
 * @param y               text Y coordinate
 */
public static void drawStringUnderlineCharAt(final Graphics g, final String text, final int underlinedIndex,
        final int x, final int y) {
    // Painting string
    drawString(g, text, x, y);

    // Painting character underline
    if (underlinedIndex >= 0 && underlinedIndex < text.length()) {
        final FontMetrics fm = g.getFontMetrics();
        g.fillRect(x + fm.stringWidth(text.substring(0, underlinedIndex)), y + fm.getDescent() - 1,
                fm.charWidth(text.charAt(underlinedIndex)), 1);
    }
}

From source file:Main.java

/**
 * Prints a <code>Document</code> using a monospaced font, word wrapping on
 * the characters ' ', '\t', '\n', ',', '.', and ';'.  This method is
 * expected to be called from Printable 'print(Graphics g)' functions.
 *
 * @param g The graphics context to write to.
 * @param doc The <code>javax.swing.text.Document</code> to print.
 * @param fontSize the point size to use for the monospaced font.
 * @param pageIndex The page number to print.
 * @param pageFormat The format to print the page with.
 * @param tabSize The number of spaces to expand tabs to.
 *
 * @see #printDocumentMonospaced/* w  w w . j a  va2s.  com*/
 */
public static int printDocumentMonospacedWordWrap(Graphics g, Document doc, int fontSize, int pageIndex,
        PageFormat pageFormat, int tabSize) {

    g.setColor(Color.BLACK);
    g.setFont(new Font("Monospaced", Font.PLAIN, fontSize));

    // Initialize our static variables (these are used by our tab expander below).
    tabSizeInSpaces = tabSize;
    fm = g.getFontMetrics();

    // Create our tab expander.
    //RPrintTabExpander tabExpander = new RPrintTabExpander();

    // Get width and height of characters in this monospaced font.
    int fontWidth = fm.charWidth('w'); // Any character will do here, since font is monospaced.
    int fontHeight = fm.getHeight();

    int MAX_CHARS_PER_LINE = (int) pageFormat.getImageableWidth() / fontWidth;
    int MAX_LINES_PER_PAGE = (int) pageFormat.getImageableHeight() / fontHeight;

    final int STARTING_LINE_NUMBER = MAX_LINES_PER_PAGE * pageIndex;

    // The (x,y) coordinate to print at (in pixels, not characters).
    // Since y is the baseline of where we'll start printing (not the top-left
    // corner), we offset it by the font's ascent ( + 1 just for good measure).
    xOffset = (int) pageFormat.getImageableX();
    int y = (int) pageFormat.getImageableY() + fm.getAscent() + 1;

    // A counter to keep track of the number of lines that WOULD HAVE been
    // printed if we were printing all lines.
    int numPrintedLines = 0;

    // Keep going while there are more lines in the document.
    currentDocLineNumber = 0; // The line number of the document we're currently on.
    rootElement = doc.getDefaultRootElement(); // To shorten accesses in our loop.
    numDocLines = rootElement.getElementCount(); // The number of lines in our document.
    while (currentDocLineNumber < numDocLines) {

        // Get the line we are going to print.
        String curLineString;
        Element currentLine = rootElement.getElement(currentDocLineNumber);
        int startOffs = currentLine.getStartOffset();
        try {
            curLineString = doc.getText(startOffs, currentLine.getEndOffset() - startOffs);
        } catch (BadLocationException ble) { // Never happens
            ble.printStackTrace();
            return Printable.NO_SUCH_PAGE;
        }

        // Remove newlines, because they end up as boxes if you don't; this is a monospaced font.
        curLineString = curLineString.replaceAll("\n", "");

        // Replace tabs with how many spaces they should be.
        if (tabSizeInSpaces == 0) {
            curLineString = curLineString.replaceAll("\t", "");
        } else {
            int tabIndex = curLineString.indexOf('\t');
            while (tabIndex > -1) {
                int spacesNeeded = tabSizeInSpaces - (tabIndex % tabSizeInSpaces);
                String replacementString = "";
                for (int i = 0; i < spacesNeeded; i++)
                    replacementString += ' ';
                // Note that "\t" is actually a regex for this method.
                curLineString = curLineString.replaceFirst("\t", replacementString);
                tabIndex = curLineString.indexOf('\t');
            }
        }

        // If this document line is too long to fit on one printed line on the page,
        // break it up into multpile lines.
        while (curLineString.length() > MAX_CHARS_PER_LINE) {

            int breakPoint = getLineBreakPoint(curLineString, MAX_CHARS_PER_LINE) + 1;

            numPrintedLines++;
            if (numPrintedLines > STARTING_LINE_NUMBER) {
                g.drawString(curLineString.substring(0, breakPoint), xOffset, y);
                y += fontHeight;
                if (numPrintedLines == STARTING_LINE_NUMBER + MAX_LINES_PER_PAGE)
                    return Printable.PAGE_EXISTS;
            }

            curLineString = curLineString.substring(breakPoint, curLineString.length());

        }

        currentDocLineNumber += 1; // We have printed one more line from the document.

        numPrintedLines++;
        if (numPrintedLines > STARTING_LINE_NUMBER) {
            g.drawString(curLineString, xOffset, y);
            y += fontHeight;
            if (numPrintedLines == STARTING_LINE_NUMBER + MAX_LINES_PER_PAGE)
                return Printable.PAGE_EXISTS;
        }

    }

    // Now, the whole document has been "printed."  Decide if this page had any text on it or not.
    if (numPrintedLines > STARTING_LINE_NUMBER)
        return Printable.PAGE_EXISTS;
    return Printable.NO_SUCH_PAGE;

}

From source file:org.esa.snap.graphbuilder.rcp.dialogs.support.GraphPanel.java

private static void drawHelp(final Graphics g) {
    final int x = (int) (g.getClipBounds().getWidth() / 2);
    final int y = (int) (g.getClipBounds().getHeight() / 2);

    final FontMetrics metrics = g.getFontMetrics();
    final String name = "Right click here to add an operator";
    final Rectangle2D rect = metrics.getStringBounds(name, g);
    final int stringWidth = (int) rect.getWidth();

    g.setColor(Color.black);/* w w  w .ja  v a2 s  .com*/
    g.drawString(name, x - stringWidth / 2, y);
}

From source file:edu.ku.brc.ui.GraphicsUtils.java

/**
 * Draws the given <code>String</code>, centered at <code>(x,y)</code>, using
 * the given graphics context./*from  ww w.  j a v  a2s .  com*/
 * 
 * @param s the string
 * @param g the graphics context to draw in
 * @param x the x coordinate for center of the <code>String</code>
 * @param y the y coordinate for center of the <code>String</code>
 */
public static void drawCenteredString(String s, Graphics g, int x, int y) {
    ((Graphics2D) g).addRenderingHints(hints);

    FontMetrics fm = g.getFontMetrics();
    int ht = fm.getAscent() + fm.getDescent();
    int width = fm.stringWidth(s);
    g.drawString(s, x - width / 2, y + (fm.getAscent() - ht / 2));
}