Example usage for java.awt FontMetrics stringWidth

List of usage examples for java.awt FontMetrics stringWidth

Introduction

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

Prototype

public int stringWidth(String str) 

Source Link

Document

Returns the total advance width for showing the specified String in this Font .

Usage

From source file:savant.view.swing.Ruler.java

/**
 * Render the background of this graphpane
 * @param g The graphics object to use//from  w ww  . ja v  a2  s .co m
 */
private void renderBackground(Graphics g) {

    Graphics2D g2 = (Graphics2D) g;

    try {

        Image image = javax.imageio.ImageIO
                .read(getClass().getResource("/savant/images/bar_selected_glossy.png"));
        Composite originalComposite = ((Graphics2D) g).getComposite();
        ((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.85F));
        g.drawImage(image, -getWidth(), 0, getWidth() * 3, getHeight(), this);
        ((Graphics2D) g).setComposite(originalComposite);
    } catch (Exception e) {
        LOG.error("Error drawing image background");
    }

    Range r = locationController.getRange();

    // At early points in the GUI initialisation, the range has not yet been set.
    if (r == null) {
        return;
    }

    int[] tickPositions = MiscUtils.getTickPositions(r);
    int separation = tickPositions.length > 1 ? tickPositions[1] - tickPositions[0] : 0;
    int xEnd = Integer.MIN_VALUE;
    FontMetrics fm = g2.getFontMetrics();

    for (int p : tickPositions) {

        int x = MiscUtils.transformPositionToPixel(p, getWidth(), r);
        if (x > xEnd + 10) {
            g2.setColor(new Color(50, 50, 50, 50)); //BrowserDefaults.colorAxisGrid);
            g2.drawLine(x, 0, x, getHeight());

            String numStr = MiscUtils.posToShortStringWithSeparation(p, separation);
            g2.setColor(Color.black);
            g2.drawString(numStr, x + 3, getHeight() / 2 + 3);
            xEnd = x + fm.stringWidth(numStr) + 3;
        }
    }

    if (r.getLength() >= locationController.getRangeStart()) {
        try {
            Image image_left_cap = javax.imageio.ImageIO
                    .read(getClass().getResource("/savant/images/round_cap_left_bordered.png"));
            int pos = getLeftCapPos();
            g.drawImage(image_left_cap, pos, 0, CAP_WIDTH, CAP_HEIGHT, this);
            g.setColor(Savant.getInstance().getBackground());
            g.fillRect(pos, 0, -getWidth(), getHeight());
        } catch (IOException ex) {
            LOG.error("Drawing failed.", ex);
        }
    }

    if (r.getLength() >= locationController.getMaxRangeEnd() - locationController.getRangeEnd()) {
        try {
            Image image_right_cap = javax.imageio.ImageIO
                    .read(getClass().getResource("/savant/images/round_cap_right_bordered.png"));
            int pos = MiscUtils.transformPositionToPixel(locationController.getMaxRangeEnd(), getWidth(),
                    locationController.getRange());
            g.drawImage(image_right_cap, pos - CAP_WIDTH, 0, CAP_WIDTH, CAP_HEIGHT, this);
            g.setColor(Savant.getInstance().getBackground());
            g.fillRect(pos, 0, this.getWidth(), this.getHeight());

        } catch (IOException ex) {
            LOG.error("Drawing failed.", ex);
        }
    }
}

From source file:com.celements.photo.image.GenerateThumbnail.java

private void drawWatermark(String watermark, Graphics2D g2d, int width, int height) {
    //TODO implement 'secure' watermark (i.e. check if this algorithm secure or can it be easily reversed?)
    g2d.setColor(new Color(255, 255, 150));
    AlphaComposite transprency = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.45f);
    g2d.setComposite(transprency);//from www .  ja v  a  2  s.  com

    FontMetrics metrics = calcWatermarkFontSize(watermark, width, g2d);
    g2d.setFont(calcWatermarkFontSize(watermark, width, g2d).getFont());

    // rotate around image center
    double angle = (Math.sin(height / (double) width));
    g2d.rotate(-angle, width / 2.0, height / 2.0);

    g2d.drawString(watermark, (width - metrics.stringWidth(watermark)) / 2,
            ((height - metrics.getHeight()) / 2) + metrics.getAscent());

    // undo rotation for correct copyright positioning
    g2d.rotate(angle, width / 2.0, height / 2.0);
}

From source file:com.celements.photo.image.GenerateThumbnail.java

private void drawString(String copyright, int width, int height, int bottomSpace, int rightSpace, int vSpacing,
        int hSpacing, FontMetrics metrics, Graphics2D g2d) {
    AlphaComposite transprency;/*from   w ww .j  a  va 2s  . c  o m*/
    g2d.setColor(new Color(255, 255, 255));
    transprency = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.66f);
    g2d.setComposite(transprency);
    //Attention: drawString's [x, y] coordinates are the baseline, not upper or lower corner.
    g2d.drawString(copyright, width - metrics.stringWidth(copyright) - hSpacing - rightSpace,
            height - metrics.getDescent() - vSpacing - bottomSpace);
}

From source file:com.quinsoft.zeidon.objectbrowser.EntitySquare.java

private void paintCenteredText(Graphics2D graphics2, int y, String text, Color color) {
    Color prevColor = graphics2.getColor();
    if (color != null)
        graphics2.setColor(color);//from  www  .  j  a  v  a2  s  .  c  o  m

    FontMetrics fm = graphics2.getFontMetrics();

    String lines[] = text.split("\n");

    // Adjust y if there is more than one line.
    y -= (lines.length - 1) * fm.getHeight() / 2;

    for (String line : lines) {
        int lth = fm.stringWidth(line);
        int mid = size.width / 2;
        graphics2.drawString(line, mid - lth / 2, y);
        y += fm.getHeight();
    }

    if (color != null)
        graphics2.setColor(prevColor);
}

From source file:BeanContainer.java

public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Color colorRetainer = g.getColor();

        g.setColor(getBackground());/*w  ww.  jav  a  2  s .c o  m*/
        g.fillRect(0, 0, getWidth(), getHeight());
        getBorder().paintBorder(this, g, 0, 0, getWidth(), getHeight());

        m_calendar.setTime(new Date()); // get current time
        int hrs = m_calendar.get(Calendar.HOUR_OF_DAY);
        int min = m_calendar.get(Calendar.MINUTE);

        g.setColor(getForeground());
        if (m_digital) {
            String time = "" + hrs + ":" + min;
            g.setFont(getFont());
            FontMetrics fm = g.getFontMetrics();
            int y = (getHeight() + fm.getAscent()) / 2;
            int x = (getWidth() - fm.stringWidth(time)) / 2;
            g.drawString(time, x, y);
        } else {
            int x = getWidth() / 2;
            int y = getHeight() / 2;
            int rh = getHeight() / 4;
            int rm = getHeight() / 3;

            double ah = ((double) hrs + min / 60.0) / 6.0 * Math.PI;
            double am = min / 30.0 * Math.PI;

            g.drawLine(x, y, (int) (x + rh * Math.sin(ah)), (int) (y - rh * Math.cos(ah)));
            g.drawLine(x, y, (int) (x + rm * Math.sin(am)), (int) (y - rm * Math.cos(am)));
        }

        g.setColor(colorRetainer);
    }

From source file:org.jboss.dashboard.commons.text.StringUtil.java

/**
 * It returns an array of subchains of maximum length in pixels.
 *
 * @param text        original string//from   w  w w  .ja  v  a  2 s.c  o  m
 * @param fontMetrics scrren font of text.
 * @param maxWidth    maximum width of subchains in pixels.
 * @return array of subchains of maximum length in pixels.
 */
public static String[] cutString(String text, FontMetrics fontMetrics, int maxWidth) {
    Vector strings = new Vector(0, 10);
    text = text.trim();
    while (!text.trim().equals("")) {
        // Search for the position where I must cut the chain.
        int cutPos = text.length();
        while (fontMetrics.stringWidth(text.substring(0, cutPos)) > maxWidth)
            cutPos--;

        // Search for a space or a separator.
        int sepPos = cutPos - 1;
        boolean foundSep = false;
        if (cutPos != text.length())
            while (sepPos > 0 && !foundSep)
                switch (text.charAt(sepPos)) {
                case ' ':
                case '.':
                case ',':
                case ';':
                case ':':
                case '?':
                    foundSep = true;
                    break;
                default:
                    sepPos--;
                }

        // If I did not find then the separator, cut the string in cutPos.
        if (!foundSep)
            sepPos = cutPos;
        else
            sepPos++;

        strings.addElement(text.substring(0, sepPos).trim());
        text = text.substring(sepPos, text.length()).trim();
    }

    String[] result = new String[strings.size()];
    for (int i = 0; i < result.length; i++)
        result[i] = (String) strings.elementAt(i);

    return result;
}

From source file:AppletMenuBarDemo.java

/**
 * Measure the menu labels, and figure out their positions, so we can
 * determine when a click happens, and so we can redraw efficiently.
 *//*from  ww  w . j ava 2  s .  co m*/
protected void measure() {
    // Get information about the font
    FontMetrics fm = this.getFontMetrics(getFont());
    // Remember the basic font size
    ascent = fm.getAscent();
    descent = fm.getDescent();
    // Create arrays to hold the measurements and positions
    int nummenus = labels.size();
    widths = new int[nummenus];
    startPositions = new int[nummenus];

    // Measure the label strings and
    // figure out the starting position of each label
    int pos = margins.left;
    for (int i = 0; i < nummenus; i++) {
        startPositions[i] = pos;
        String label = (String) labels.elementAt(i);
        widths[i] = fm.stringWidth(label);
        pos += widths[i] + spacing;
    }

    // Compute our preferred size from this data
    prefsize.width = pos - spacing + margins.right;
    prefsize.height = ascent + descent + margins.top + margins.bottom;

    // We've don't need to be remeasured anymore.
    remeasure = false;
}

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

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    boolean doScale = true;

    int w = getWidth();
    int h = getHeight();

    Image dspImg = image;//from w  w  w .j  av  a2 s.c o m
    boolean doDisplayImage = (image != null && (!isNoAttachment && status == kImageOK)) || isLoading;
    if (isLoading) {
        doDisplayImage = true;
        dspImg = IconManager.getImage("Loading").getImage();
    }
    if (doDisplayImage && dspImg != null) {
        int imgW = dspImg.getWidth(null);
        int imgH = dspImg.getHeight(null);

        if (doScale && (imgW > w || imgH > h)) {
            double scaleW = 1.0;
            double scaleH = 1.0;
            double scale = 1.0;

            if (imgW > w) {
                scaleW = (double) w / imgW;
            }
            if (imgH > h) {
                scaleH = (double) h / imgH;
            }
            scale = Math.min(scaleW, scaleH);

            imgW = (int) (imgW * scale);
            imgH = (int) (imgH * scale);
        }

        int x = 0;
        int y = 0;

        if (imgW < w) {
            x = (w - imgW) / 2;
        }
        if (imgH < h) {
            y = (h - imgH) / 2;
        }
        g.drawImage(dspImg, x, y, imgW, imgH, null);

    } else if (doShowText) {
        GraphicsUtils.turnOnAntialiasedDrawing(g);
        String[] label = this.isNoAttachment ? (isFullImage ? noAttachmentStr : noThumnailStr)
                : loadingAttachmentStr;
        FontMetrics fm = g.getFontMetrics();
        int spacing = 2;
        int yOffset = (h - (fm.getHeight() + spacing) * label.length) / 2;
        if (yOffset < 0)
            yOffset = 0;
        int y = yOffset + fm.getHeight();
        for (String str : label) {
            g.drawString(str, (w - fm.stringWidth(str)) / 2, y);
            y += fm.getHeight() + 2;
        }
    }
}

From source file:pl.otros.logview.gui.LogViewPanel.java

private void updateTimeColumnSize() {
    FontMetrics fm = table.getFontMetrics(table.getFont());
    int dateWidth = fm.stringWidth(
            new SimpleDateFormat(configuration.getString(ConfKeys.LOG_TABLE_FORMAT_DATE_FORMAT, "HH:mm:ss.SSS"))
                    .format(new Date()));
    updateColumnSizeIfVisible(TableColumns.TIME, dateWidth + 1, dateWidth + 1);
}

From source file:pl.otros.logview.gui.LogViewPanel.java

private void updateLevelColumnSize() {
    FontMetrics fm = table.getFontMetrics(table.getFont());
    int levelWidth = fm.stringWidth(Level.WARNING.getName());

    switch (configuration.get(LevelRenderer.Mode.class, ConfKeys.LOG_TABLE_FORMAT_LEVEL_RENDERER,
            LevelRenderer.Mode.IconsOnly)) {
    case IconsOnly:
        updateColumnSizeIfVisible(TableColumns.LEVEL, 16 + 1, 16 + 1);
        break;/*from w  w  w  .ja va 2  s .c  o m*/
    case IconsAndText:
        updateColumnSizeIfVisible(TableColumns.LEVEL, 16 + levelWidth + 5, 16 + levelWidth + 5);
        break;
    case TextOnly:
        updateColumnSizeIfVisible(TableColumns.LEVEL, levelWidth + 1, levelWidth + 1);
        break;
    }
}