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 abstract FontMetrics getFontMetrics(Font f);

Source Link

Document

Gets the font metrics for the specified font.

Usage

From source file:com.limegroup.gnutella.gui.GUIUtils.java

/**
 * It will adjust the column width to match the widest element.
 * (You might not want to use this for every column, consider some columns might be really long)
 * @param model/* w w w  .j  a v  a  2  s  . c  om*/
 * @param columnIndex
 * @param table
 * @return
 */
public static void adjustColumnWidth(TableModel model, int columnIndex, int maxWidth, int rightPadding,
        JTable table) {

    if (columnIndex > model.getColumnCount() - 1) {
        //invalid column index
        return;
    }

    if (!model.getColumnClass(columnIndex).equals(String.class)) {
        return;
    }

    String longestValue = "";
    for (int row = 0; row < model.getRowCount(); row++) {
        String strValue = (String) model.getValueAt(row, columnIndex);
        if (strValue != null && strValue.length() > longestValue.length()) {
            longestValue = strValue;
        }
    }

    Graphics g = table.getGraphics();

    try {
        int suggestedWidth = (int) g.getFontMetrics(table.getFont()).getStringBounds(longestValue, g)
                .getWidth();
        table.getColumnModel().getColumn(columnIndex)
                .setPreferredWidth(((suggestedWidth > maxWidth) ? maxWidth : suggestedWidth) + rightPadding);
    } catch (Exception e) {
        table.getColumnModel().getColumn(columnIndex).setPreferredWidth(maxWidth);
        e.printStackTrace();
    }

}

From source file:Main.java

public void paint(Graphics g) {
    v = g.getFontMetrics(getFont()).getHeight() + 1;
    int j = 0;/*  w  w  w .  ja va2  s. c  om*/
    int k = s.length();
    while (j < k + 1) {
        if (j == k)
            g.drawString(s.substring(j), 10, 10 + (j * v));
        else
            g.drawString(s.substring(j, j + 1), 10, 10 + (j * v));
        j++;
    }
}

From source file:Main.java

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    FontMetrics fm = g.getFontMetrics(font);
    wordWidth = fm.stringWidth(word);//from w ww  .j  a  v a2s .c om
    wordHeight = fm.getAscent();

    g.setFont(new Font("impact", Font.PLAIN, 28));
    g.setColor(Color.BLUE);
    g.drawString(word, x, y);
}

From source file:Main.java

public void paint(Graphics g) {

    int fontSize = 20;

    Font font = new Font("TimesRoman", Font.PLAIN, fontSize);
    g.setFont(font);//from   ww w. j  a va  2s. c  om

    FontMetrics fm = g.getFontMetrics(font);

    String s = "www.java2s.com";

    int stringWidth = fm.stringWidth(s);

    int w = 200;
    int h = 200;

    int x = (w - stringWidth) / 2;
    int baseline = fm.getMaxAscent() + (h - (fm.getAscent() + fm.getMaxDecent())) / 2;
    int ascent = fm.getMaxAscent();
    int descent = fm.getMaxDecent();
    int fontHeight = fm.getMaxAscent() + fm.getMaxDecent();

    g.setColor(Color.white);
    g.fillRect(x, baseline - ascent, stringWidth, fontHeight);

    g.setColor(Color.gray);
    g.drawLine(x, baseline, x + stringWidth, baseline);

    g.setColor(Color.red);
    g.drawLine(x, baseline + descent, x + stringWidth, baseline + descent);

    g.setColor(Color.blue);
    g.drawLine(x, baseline - ascent, x + stringWidth, baseline - ascent);
    g.setColor(Color.black);
    g.drawString(s, x, baseline);

}

From source file:FontPanel.java

public void paintComponent(Graphics g) {
    super.paintComponent(g);

    Font f = new Font("SansSerif", Font.BOLD, 14);
    Font fi = new Font("SansSerif", Font.BOLD + Font.ITALIC, 14);
    FontMetrics fm = g.getFontMetrics(f);
    FontMetrics fim = g.getFontMetrics(fi);

    String s1 = "Java ";
    String s2 = "Source and Support";
    String s3 = " at www.java2s.com";
    int width1 = fm.stringWidth(s1);
    int width2 = fim.stringWidth(s2);
    int width3 = fm.stringWidth(s3);

    Dimension d = getSize();//from  ww  w.ja va  2 s.c  om
    int cx = (d.width - width1 - width2 - width3) / 2;
    int cy = (d.height - fm.getHeight()) / 2 + fm.getAscent();

    g.setFont(f);
    g.drawString(s1, cx, cy);
    cx += width1;
    g.setFont(fi);
    g.drawString(s2, cx, cy);
    cx += width2;
    g.setFont(f);
    g.drawString(s3, cx, cy);
}

From source file:Main.java

public Component getListCellRendererComponent(final JList list, final Object value, final int index,
        final boolean isSelected, final boolean cellHasFocus) {
    return new JPanel() {
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Font font = (Font) value;
            String text = font.getFamily();
            FontMetrics fm = g.getFontMetrics(font);
            g.setColor(isSelected ? list.getSelectionBackground() : list.getBackground());
            g.fillRect(0, 0, getWidth(), getHeight());
            g.setColor(isSelected ? list.getSelectionForeground() : list.getForeground());
            g.setFont(font);/*from  w w  w . j a v a2  s. c om*/
            g.drawString(text, 0, fm.getAscent());
        }

        public Dimension getPreferredSize() {
            Font font = (Font) value;
            String text = font.getFamily();
            Graphics g = getGraphics();
            FontMetrics fm = g.getFontMetrics(font);
            return new Dimension(fm.stringWidth(text), fm.getHeight());
        }
    };
}

From source file:PaginationExample.java

public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException {

    Font font = new Font("Serif", Font.PLAIN, 10);
    FontMetrics metrics = g.getFontMetrics(font);
    int lineHeight = metrics.getHeight();

    if (pageBreaks == null) {
        initTextLines();/*  w  w  w . j ava2s.  c  o m*/
        int linesPerPage = (int) (pf.getImageableHeight() / lineHeight);
        int numBreaks = (textLines.length - 1) / linesPerPage;
        pageBreaks = new int[numBreaks];
        for (int b = 0; b < numBreaks; b++) {
            pageBreaks[b] = (b + 1) * linesPerPage;
        }
    }

    if (pageIndex > pageBreaks.length) {
        return NO_SUCH_PAGE;
    }

    /*
     * User (0,0) is typically outside the imageable area, so we must translate
     * by the X and Y values in the PageFormat to avoid clipping Since we are
     * drawing text we
     */
    Graphics2D g2d = (Graphics2D) g;
    g2d.translate(pf.getImageableX(), pf.getImageableY());

    /*
     * Draw each line that is on this page. Increment 'y' position by lineHeight
     * for each line.
     */
    int y = 0;
    int start = (pageIndex == 0) ? 0 : pageBreaks[pageIndex - 1];
    int end = (pageIndex == pageBreaks.length) ? textLines.length : pageBreaks[pageIndex];
    for (int line = start; line < end; line++) {
        y += lineHeight;
        g.drawString(textLines[line], 0, y);
    }

    /* tell the caller that this page is part of the printed document */
    return PAGE_EXISTS;
}

From source file:org.opensha.commons.util.FileUtils.java

/**
 * Prints a Text file//from  w w  w .j a  va  2s .co m
 * @param pjob PrintJob  created using getToolkit().getPrintJob(JFrame,String,Properties);
 * @param pg Graphics
 * @param textToPrint String
 */
public static void print(PrintJob pjob, Graphics pg, String textToPrint) {

    int margin = 60;

    int pageNum = 1;
    int linesForThisPage = 0;
    int linesForThisJob = 0;
    // Note: String is immutable so won't change while printing.
    if (!(pg instanceof PrintGraphics)) {
        throw new IllegalArgumentException("Graphics context not PrintGraphics");
    }
    StringReader sr = new StringReader(textToPrint);
    LineNumberReader lnr = new LineNumberReader(sr);
    String nextLine;
    int pageHeight = pjob.getPageDimension().height - margin;
    Font helv = new Font("Monaco", Font.PLAIN, 12);
    //have to set the font to get any output
    pg.setFont(helv);
    FontMetrics fm = pg.getFontMetrics(helv);
    int fontHeight = fm.getHeight();
    int fontDescent = fm.getDescent();
    int curHeight = margin;
    try {
        do {
            nextLine = lnr.readLine();
            if (nextLine != null) {
                if ((curHeight + fontHeight) > pageHeight) {
                    // New Page
                    if (linesForThisPage == 0)
                        break;

                    pageNum++;
                    linesForThisPage = 0;
                    pg.dispose();
                    pg = pjob.getGraphics();
                    if (pg != null) {
                        pg.setFont(helv);
                    }
                    curHeight = 0;
                }
                curHeight += fontHeight;
                if (pg != null) {
                    pg.drawString(nextLine, margin, curHeight - fontDescent);
                    linesForThisPage++;

                    linesForThisJob++;
                }
            }
        } while (nextLine != null);
    } catch (EOFException eof) {
        // Fine, ignore
    } catch (Throwable t) { // Anything else
        t.printStackTrace();
    }
}

From source file:com.cburch.logisim.gui.start.AboutCredits.java

@Override
protected void paintComponent(Graphics g) {
    FontMetrics[] fms = new FontMetrics[font.length];
    for (int i = 0; i < fms.length; i++) {
        fms[i] = g.getFontMetrics(font[i]);
    }//from w ww .ja  va2s  .c  o m
    if (linesHeight == 0) {
        int y = 0;
        int index = -1;
        for (CreditsLine line : lines) {
            index++;
            if (index == initialLines)
                initialHeight = y;
            if (line.type == 0)
                y += 10;
            FontMetrics fm = fms[line.type];
            line.y = y + fm.getAscent();
            y += fm.getHeight();
        }
        linesHeight = y;
    }

    Paint[] paint = paintSteady;
    int yPos = 0;
    int height = getHeight();
    int initY = Math.min(0, initialHeight - height + About.IMAGE_BORDER);
    int maxY = linesHeight - height - initY;
    int totalMillis = 2 * MILLIS_FREEZE + (linesHeight + height) * MILLIS_PER_PIXEL;
    int offs = scroll % totalMillis;
    if (offs >= 0 && offs < MILLIS_FREEZE) {
        // frozen before starting the credits scroll
        int a = 255 * (MILLIS_FREEZE - offs) / MILLIS_FREEZE;
        if (a > 245) {
            paint = null;
        } else if (a < 15) {
            paint = paintSteady;
        } else {
            paint = new Paint[colorBase.length];
            for (int i = 0; i < paint.length; i++) {
                Color hue = colorBase[i];
                paint[i] = new GradientPaint(0.0f, 0.0f, derive(hue, a), 0.0f, fadeStop, hue);
            }
        }
        yPos = initY;
    } else if (offs < MILLIS_FREEZE + maxY * MILLIS_PER_PIXEL) {
        // scrolling through credits
        yPos = initY + (offs - MILLIS_FREEZE) / MILLIS_PER_PIXEL;
    } else if (offs < 2 * MILLIS_FREEZE + maxY * MILLIS_PER_PIXEL) {
        // freezing at bottom of scroll
        yPos = initY + maxY;
    } else if (offs < 2 * MILLIS_FREEZE + (linesHeight - initY) * MILLIS_PER_PIXEL) {
        // scrolling bottom off screen
        yPos = initY + (offs - 2 * MILLIS_FREEZE) / MILLIS_PER_PIXEL;
    } else {
        // scrolling next credits onto screen
        int millis = offs - 2 * MILLIS_FREEZE - (linesHeight - initY) * MILLIS_PER_PIXEL;
        paint = null;
        yPos = -height + millis / MILLIS_PER_PIXEL;
    }

    int width = getWidth();
    int centerX = width / 2;
    maxY = getHeight();
    for (CreditsLine line : lines) {
        int y = line.y - yPos;
        if (y < -100 || y > maxY + 50)
            continue;

        int type = line.type;
        if (paint == null) {
            g.setColor(colorBase[type]);
        } else {
            ((Graphics2D) g).setPaint(paint[type]);
        }
        g.setFont(font[type]);
        int textWidth = fms[type].stringWidth(line.text);
        g.drawString(line.text, centerX - textWidth / 2, line.y - yPos);

        Image img = line.img;
        if (img != null) {
            int x = width - line.imgWidth - About.IMAGE_BORDER;
            int top = y - fms[type].getAscent();
            g.drawImage(img, x, top, this);
        }
    }
}

From source file:org.esa.nest.dat.views.polarview.Axis.java

public void draw(Graphics g) {
    if (!visible)
        return;/*ww  w  .j  a  v  a 2 s.co m*/
    gr.setGraphics(g);
    final FontMetrics fm = g.getFontMetrics(font);
    g.setColor(axisColor);
    gr.drawLine(0, 0, length + 2 * spacing, 0);
    int tickLength = this.tickLength;
    if (ticksInside)
        tickLength = -tickLength;
    final int maxTickCount = (int) (((float) length + 0.5F)
            / (float) gr.maxTickSize(tickNames, tickCount, font));
    final int minTickCount = Math.min(maxTickCount, bestTickCount);
    if (tickCount > maxTickCount)
        setTickCount(maxTickCount);
    else if (tickCount < minTickCount)
        setTickCount(minTickCount);
    for (int i = 0; i < tickCount; i++) {
        gr.drawTick(tickPos[i], tickLength);
    }
    g.setColor(labelColor);
    g.setFont(font);
    for (int i = 0; i < tickCount; i++) {
        gr.drawMultiLineTickName(tickNames[i], tickPos[i], tickLength, fm);
    }

    g.setFont(titleFont);
    gr.drawTitle(title, titleFont, length);
    if (!withGrid)
        return;
    g.setColor(gridColor);
    for (int i = 0; i < tickCount; i++) {
        gr.drawTick(tickPos[i], breadth);
    }
}