Example usage for java.awt FontMetrics getHeight

List of usage examples for java.awt FontMetrics getHeight

Introduction

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

Prototype

public int getHeight() 

Source Link

Document

Gets the standard height of a line of text in this font.

Usage

From source file:StringRectPaintPanel.java

public void paint(Graphics g) {
    g.setFont(new Font("", 0, 100));
    FontMetrics fm = getFontMetrics(new Font("", 0, 100));
    String s = "java2s";
    int x = 5;/*from w w w.ja v  a  2  s .  co m*/
    int y = 5;

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

        int h = fm.getHeight();
        int w = fm.charWidth(c);

        g.drawRect(x, y, w, h);
        g.drawString(String.valueOf(c), x, y + h);

        x = x + w;
    }
}

From source file:ala.soils2sat.DrawingUtils.java

public static Rectangle drawString(Graphics g, Font font, String text, int x, int y, int width, int height,
        int align, boolean wrap) {
    g.setFont(font);//  www  . jav  a2 s  .co m
    FontMetrics fm = g.getFontMetrics(font);

    setPreferredAliasingMode(g);

    Rectangle ret = new Rectangle(0, 0, 0, 0);

    if (text == null) {
        return ret;
    }
    String[] alines = text.split("\\n");
    ArrayList<String> lines = new ArrayList<String>();
    for (String s : alines) {
        if (wrap && fm.stringWidth(s) > width) {
            // need to split this up into multiple lines...
            List<String> splitLines = wrapString(s, fm, width);
            lines.addAll(splitLines);
        } else {
            lines.add(s);
        }
    }
    int numlines = lines.size();
    while (fm.getHeight() * numlines > height) {
        numlines--;
    }
    if (numlines > 0) {
        int maxwidth = 0;
        int minxoffset = y + width;
        int totalheight = (numlines * fm.getHeight());

        int linestart = ((height / 2) - (totalheight / 2));

        if (!wrap) {
            ret.y = y + linestart;
        } else {
            ret.y = y;
            linestart = 0;
        }
        for (int idx = 0; idx < numlines; ++idx) {
            String line = lines.get(idx);
            int stringWidth = fm.stringWidth(line);
            // the width of the label depends on the font :
            // if the width of the label is larger than the item
            if (stringWidth > 0 && width < stringWidth) {
                // We have to truncate the label
                line = clipString(null, fm, line, width);
                stringWidth = fm.stringWidth(line);
            }

            int xoffset = 0;
            int yoffset = linestart + fm.getHeight() - fm.getDescent();
            if (align == TEXT_ALIGN_RIGHT) {
                xoffset = (width - stringWidth);
            } else if (align == TEXT_ALIGN_CENTER) {
                xoffset = (int) Math.round((double) (width - stringWidth) / (double) 2);
            }

            if (xoffset < minxoffset) {
                minxoffset = xoffset;
            }
            g.drawString(line, x + xoffset, y + yoffset);
            if (stringWidth > maxwidth) {
                maxwidth = stringWidth;
            }
            linestart += fm.getHeight();
        }

        ret.width = maxwidth;
        ret.height = totalheight;
        ret.x = x + minxoffset;

        // Debug only...
        if (DEBUG) {
            Graphics2D g2d = (Graphics2D) g;
            g2d.setStroke(new BasicStroke(1));
            g.setColor(Color.blue);
            g.drawRect(ret.x, ret.y, ret.width, ret.height);
            g.setColor(Color.green);
            g.drawRect(x, y, width, height);
        }

        return ret;
    }
    return ret;
}

From source file:Main.java

public void paint(Graphics g) {
    g.setFont(new Font("SansSerif", Font.BOLD, 12));
    FontMetrics fm = g.getFontMetrics();
    g.drawString("Current font: " + g.getFont(), 10, 40);
    g.drawString("Ascent: " + fm.getAscent(), 10, 55);
    g.drawString("Descent: " + fm.getDescent(), 10, 70);
    g.drawString("Height: " + fm.getHeight(), 10, 85);
    g.drawString("Leading: " + fm.getLeading(), 10, 100);

    Font font = new Font("Serif", Font.ITALIC, 14);
    fm = g.getFontMetrics(font);//from w  w w  . j  a  v  a 2s .com
    g.setFont(font);
    g.drawString("Current font: " + font, 10, 130);
    g.drawString("Ascent: " + fm.getAscent(), 10, 145);
    g.drawString("Descent: " + fm.getDescent(), 10, 160);
    g.drawString("Height: " + fm.getHeight(), 10, 175);
    g.drawString("Leading: " + fm.getLeading(), 10, 190);
}

From source file:org.cybercat.automation.addons.common.ScreenshotManager.java

public BufferedImage applySubs(BufferedImage image, String text) {
    Graphics2D g2 = image.createGraphics();
    g2.setFont(font);//  ww w. j  a  va 2 s.c  om

    int height = image.getHeight();
    int width = image.getWidth();

    g2.setColor(fontColor);

    String[] subs = text.split("\n");
    FontMetrics fMetrics = g2.getFontMetrics();
    int lineHeight = fMetrics.getHeight();
    int lineWidth;
    for (int i = subs.length; i > 0; i--) {
        lineWidth = fMetrics.stringWidth(subs[i - 1]);
        int y = height - bottomOffset - ((subs.length - i) * (lineHeight + lineOffset));
        int x = (width / 2) - (lineWidth / 2);
        g2.drawString(subs[i - 1], x, y);
    }
    g2.dispose();
    return image;
}

From source file:WalkingText.java

/** Applet Initializer */
public void init() {
    xloc = 0;/*w  w w.ja v a 2 s .c om*/
    width = getSize().width;
    height = getSize().height;

    if ((mesg = getParameter("text")) == null)
        mesg = "Hello World of Java";

    String pSize = getParameter("fontsize");
    if (pSize == null)
        pSize = "12";

    String fontName = getParameter("fontName");
    if (fontName == null)
        fontName = "Helvetica";

    // System.out.println("Font is " + pSize + " point " + fontName);
    Font f = new Font(fontName, Font.PLAIN, Integer.parseInt(pSize));
    setFont(f);

    FontMetrics fm = getToolkit().getFontMetrics(f);
    textWidth = fm.stringWidth(mesg);
    textHeight = fm.getHeight();
    // System.out.println("TextWidth " + textWidth + ", ht " + textHeight);

    // use textHeight in y coordinate calculation
    yloc = height - ((height - textHeight) / 2);
}

From source file:Base64.java

/**
 * Draws a line on the screen at the specified index. Default is green.
 * <p/>/*from  w  w  w . j ava2  s .  c o m*/
 * Available colours: red, green, cyan, purple, white.
 *
 * @param render The Graphics object to be used.
 * @param row    The index where you want the text.
 * @param text   The text you want to render. Colours can be set like [red].
 */
public static void drawLine(Graphics render, int row, String text) {
    FontMetrics metrics = render.getFontMetrics();
    int height = metrics.getHeight() + 4; // height + gap
    int y = row * height + 15 + 19;
    String[] texts = text.split("\\[");
    int xIdx = 7;
    Color cur = Color.GREEN;
    for (String t : texts) {
        for (@SuppressWarnings("unused")
        String element : COLOURS_STR) {
            // String element = COLOURS_STR[i];
            // Don't search for a starting '[' cause it they don't exists.
            // we split on that.
            int endIdx = t.indexOf(']');
            if (endIdx != -1) {
                String colorName = t.substring(0, endIdx);
                if (COLOR_MAP.containsKey(colorName)) {
                    cur = COLOR_MAP.get(colorName);
                } else {
                    try {
                        Field f = Color.class.getField(colorName);
                        int mods = f.getModifiers();
                        if (Modifier.isPublic(mods) && Modifier.isStatic(mods) && Modifier.isFinal(mods)) {
                            cur = (Color) f.get(null);
                            COLOR_MAP.put(colorName, cur);
                        }
                    } catch (Exception ignored) {
                    }
                }
                t = t.replace(colorName + "]", "");
            }
        }
        render.setColor(Color.BLACK);
        render.drawString(t, xIdx, y + 1);
        render.setColor(cur);
        render.drawString(t, xIdx, y);
        xIdx += metrics.stringWidth(t);
    }
}

From source file:Main.java

/**
 * Returns the {@link Dimension} for the given {@link JTextComponent}
 * subclass that will show the whole word wrapped text in the given width.
 * It won't work for styled text of varied size or style, it's assumed that
 * the whole text is rendered with the {@link JTextComponent}s font.
 *
 * @param textComponent the {@link JTextComponent} to calculate the {@link Dimension} for
 * @param width the width of the resulting {@link Dimension}
 * @param text the {@link String} which should be word wrapped
 * @return The calculated {@link Dimension}
 *//*from www . j  a va 2 s .com*/
public static Dimension getWordWrappedTextDimension(JTextComponent textComponent, int width, String text) {
    if (textComponent == null) {
        throw new IllegalArgumentException("textComponent cannot be null");
    }
    if (width < 1) {
        throw new IllegalArgumentException("width must be 1 or greater");
    }
    if (text == null) {
        text = textComponent.getText();
    }
    if (text.isEmpty()) {
        return new Dimension(width, 0);
    }

    FontMetrics metrics = textComponent.getFontMetrics(textComponent.getFont());
    FontRenderContext rendererContext = metrics.getFontRenderContext();
    float formatWidth = width - textComponent.getInsets().left - textComponent.getInsets().right;

    int lines = 0;
    String[] paragraphs = text.split("\n");
    for (String paragraph : paragraphs) {
        if (paragraph.isEmpty()) {
            lines++;
        } else {
            AttributedString attributedText = new AttributedString(paragraph);
            attributedText.addAttribute(TextAttribute.FONT, textComponent.getFont());
            AttributedCharacterIterator charIterator = attributedText.getIterator();
            LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(charIterator, rendererContext);

            lineMeasurer.setPosition(charIterator.getBeginIndex());
            while (lineMeasurer.getPosition() < charIterator.getEndIndex()) {
                lineMeasurer.nextLayout(formatWidth);
                lines++;
            }
        }
    }

    return new Dimension(width,
            metrics.getHeight() * lines + textComponent.getInsets().top + textComponent.getInsets().bottom);
}

From source file:Center.java

License:asdf

public void addNotify() {
    super.addNotify();
    int maxWidth = 0;
    FontMetrics fm = getFontMetrics(getFont());
    for (int i = 0; i < text.length; i++) {
        maxWidth = Math.max(maxWidth, fm.stringWidth(text[i]));
    }/*from   w  w w.  j a  va2 s.  c  om*/
    Insets inset = getInsets();
    dim = new Dimension(maxWidth + inset.left + inset.right,
            text.length * fm.getHeight() + inset.top + inset.bottom);
    setSize(dim);
}

From source file:net.sf.mzmine.modules.visualization.scatterplot.scatterplotchart.ScatterPlotRenderer.java

/**
 * Draws an item label.//from w w  w .ja v a 2 s  . c  o  m
 * 
 * @param g2
 *            the graphics device.
 * @param orientation
 *            the orientation.
 * @param dataset
 *            the dataset.
 * @param series
 *            the series index (zero-based).
 * @param item
 *            the item index (zero-based).
 * @param x
 *            the x coordinate (in Java2D space).
 * @param y
 *            the y coordinate (in Java2D space).
 * @param negative
 *            indicates a negative value (which affects the item label
 *            position).
 */
protected void drawItemLabel(Graphics2D g2, PlotOrientation orientation, XYDataset dataset, int series,
        int item, double x, double y, boolean negative) {

    XYItemLabelGenerator generator = getItemLabelGenerator(series, item);
    Font labelFont = getItemLabelFont(series, item);
    g2.setFont(labelFont);
    String label = generator.generateLabel(dataset, series, item);

    if ((label == null) || (label.length() == 0))
        return;

    // get the label position..
    ItemLabelPosition position = null;
    if (!negative) {
        position = getPositiveItemLabelPosition(series, item);
    } else {
        position = getNegativeItemLabelPosition(series, item);
    }

    // work out the label anchor point...
    Point2D anchorPoint = calculateLabelAnchorPoint(position.getItemLabelAnchor(), x, y, orientation);

    FontMetrics metrics = g2.getFontMetrics(labelFont);
    int width = SwingUtilities.computeStringWidth(metrics, label) + 2;
    int height = metrics.getHeight();

    int X = (int) (anchorPoint.getX() - (width / 2));
    int Y = (int) (anchorPoint.getY() - (height));

    g2.setPaint(searchColor);
    g2.fillRect(X, Y, width, height);

    super.drawItemLabel(g2, orientation, dataset, series, item, x, y, negative);

}

From source file:JapaneseCalendar.java

public void paintComponent(Graphics g) {
    int width = 400;
    int height = 400;

    Calendar cal = Calendar.getInstance(locale);
    cal.setTime(new Date());

    String header = cal.getDisplayName(Calendar.MONTH, Calendar.LONG, locale);
    header += " " + cal.get(Calendar.YEAR);

    FontMetrics fm = g.getFontMetrics();
    Insets insets = getInsets();/*from w  ww.  j  a v  a2s.com*/
    g.setColor(Color.black);
    g.drawString(header, (width - fm.stringWidth(header)) / 2, insets.top + fm.getHeight());

    DateFormatSymbols dfs = new DateFormatSymbols(locale);
    String[] weekdayNames = dfs.getShortWeekdays();
    int fieldWidth = (width - insets.left - insets.right) / 7;
    g.drawString(weekdayNames[Calendar.SUNDAY],
            insets.left + (fieldWidth - fm.stringWidth(weekdayNames[Calendar.SUNDAY])) / 2,
            insets.top + 3 * fm.getHeight());
    g.drawString(weekdayNames[Calendar.MONDAY],
            insets.left + fieldWidth + (fieldWidth - fm.stringWidth(weekdayNames[Calendar.MONDAY])) / 2,
            insets.top + 3 * fm.getHeight());
    g.drawString(weekdayNames[Calendar.TUESDAY],
            insets.left + 2 * fieldWidth + (fieldWidth - fm.stringWidth(weekdayNames[Calendar.TUESDAY])) / 2,
            insets.top + 3 * fm.getHeight());
    g.drawString(weekdayNames[Calendar.WEDNESDAY],
            insets.left + 3 * fieldWidth + (fieldWidth - fm.stringWidth(weekdayNames[Calendar.WEDNESDAY])) / 2,
            insets.top + 3 * fm.getHeight());
    g.drawString(weekdayNames[Calendar.THURSDAY],
            insets.left + 4 * fieldWidth + (fieldWidth - fm.stringWidth(weekdayNames[Calendar.THURSDAY])) / 2,
            insets.top + 3 * fm.getHeight());
    g.drawString(weekdayNames[Calendar.FRIDAY],
            insets.left + 5 * fieldWidth + (fieldWidth - fm.stringWidth(weekdayNames[Calendar.FRIDAY])) / 2,
            insets.top + 3 * fm.getHeight());
    g.drawString(weekdayNames[Calendar.SATURDAY],
            insets.left + 6 * fieldWidth + (fieldWidth - fm.stringWidth(weekdayNames[Calendar.SATURDAY])) / 2,
            insets.top + 3 * fm.getHeight());

    int dom = cal.get(Calendar.DAY_OF_MONTH);
    cal.set(Calendar.DAY_OF_MONTH, 1);
    int col = 0;
    switch (cal.get(Calendar.DAY_OF_WEEK)) {
    case Calendar.MONDAY:
        col = 1;
        break;

    case Calendar.TUESDAY:
        col = 2;
        break;

    case Calendar.WEDNESDAY:
        col = 3;
        break;

    case Calendar.THURSDAY:
        col = 4;
        break;

    case Calendar.FRIDAY:
        col = 5;
        break;

    case Calendar.SATURDAY:
        col = 6;
    }
    cal.set(Calendar.DAY_OF_MONTH, dom);

    int row = 5 * fm.getHeight();
    for (int i = 1; i <= cal.getActualMaximum(Calendar.DAY_OF_MONTH); i++) {
        g.drawString("" + i, insets.left + fieldWidth * col + (fieldWidth - fm.stringWidth("" + i)) / 2, row);
        if (++col > 6) {
            col = 0;
            row += fm.getHeight();
        }
    }
}