Java Code Examples for java.awt.FontMetrics#getMaxAscent()

The following examples show how to use java.awt.FontMetrics#getMaxAscent() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Quelea   File: Utils.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Calculates the largest size of the given font for which the given string
 * will fit into the given size.
 * <p/>
 * @param g the graphics to use in the current context.
 * @param font the original font to base the returned font on.
 * @param string the string to fit.
 * @param width the maximum width available.
 * @param height the maximum height available.
 * @return the maximum font size that fits into the given area.
 */
public static int getMaxFittingFontSize(Graphics g, Font font, String string, int width, int height) {
	int minSize = 0;
	int maxSize = 288;
	int curSize = font.getSize();

	while (maxSize - minSize > 2) {
		FontMetrics fm = g.getFontMetrics(new Font(font.getName(), font.getStyle(), curSize));
		int fontWidth = fm.stringWidth(string);
		int fontHeight = fm.getLeading() + fm.getMaxAscent() + fm.getMaxDescent();

		if ((fontWidth > width) || (fontHeight > height)) {
			maxSize = curSize;
			curSize = (maxSize + minSize) / 2;
		} else {
			minSize = curSize;
			curSize = (minSize + maxSize) / 2;
		}
	}

	return curSize;
}
 
Example 2
@Override
public Dimension getMinimumSize() {
    Dimension minSize = new Dimension();

    if (superIsButton) {
        minSize = super.getMinimumSize();
    } else {

        Graphics g = getGraphics();
        FontMetrics metrics = g.getFontMetrics();

        minSize.width = metrics.stringWidth(labelString) + 14;
        minSize.height = metrics.getMaxAscent()
                + metrics.getMaxDescent() + 9;

        g.dispose();
        g = null;
    }
    return minSize;
}
 
Example 3
Source Project: constellation   File: HistogramDisplay.java    License: Apache License 2.0 5 votes vote down vote up
private int setFontToFit(final Graphics g, final int barSize) {
    int fontSize = MAXIMUM_BAR_HEIGHT - 4;
    int size;
    Font font;
    FontMetrics metrics;

    do {
        font = FONT.deriveFont((float) fontSize);
        metrics = g.getFontMetrics(font);
        size = metrics.getMaxAscent() + metrics.getMaxDescent();
    } while (--fontSize > MIN_FONT_SIZE && size > barSize - 4);

    g.setFont(font);
    return Math.round(size / 2f) - metrics.getMaxDescent();
}
 
Example 4
Source Project: netbeans   File: HtmlLabelUI.java    License: Apache License 2.0 5 votes vote down vote up
private void paintIconAndTextCentered(Graphics g, HtmlRendererImpl r) {
    Insets ins = r.getInsets();
    Icon ic = r.getIcon();
    int w = r.getWidth() - (ins.left + ins.right);
    int txtX = ins.left;
    int txtY = 0;

    if ((ic != null) && (ic.getIconWidth() > 0) && (ic.getIconHeight() > 0)) {
        int iconx = (w > ic.getIconWidth()) ? ((w / 2) - (ic.getIconWidth() / 2)) : txtX;
        int icony = 0;
        ic.paintIcon(r, g, iconx, icony);
        txtY += (ic.getIconHeight() + r.getIconTextGap());
    }

    int txtW = r.getPreferredSize().width;
    txtX = (txtW < r.getWidth()) ? ((r.getWidth() / 2) - (txtW / 2)) : 0;

    int txtH = r.getHeight() - txtY;

    Font f = font(r);
    g.setFont(f);

    FontMetrics fm = g.getFontMetrics(f);
    txtY += fm.getMaxAscent();

    Color background = getBackgroundFor(r);
    Color foreground = ensureContrastingColor(getForegroundFor(r), background);

    if (r.isHtml()) {
        HtmlRenderer._renderHTML(
            r.getText(), 0, g, txtX, txtY, txtW, txtH, f, foreground, r.getRenderStyle(), true, background, r.isSelected()
        );
    } else {
        HtmlRenderer.renderString(
            r.getText(), g, txtX, txtY, txtW, txtH, f, foreground, r.getRenderStyle(), true
        );
    }
}
 
Example 5
@Override
public void paint(Graphics g) {

    super.paint(g);
    Rectangle bounds = getBounds();
    if (superIsButton) {
        return;
    }
    Dimension size = getSize();
    Color oldColor = g.getColor();

    // draw border
    g.setColor(getBackground());
    g.fill3DRect(0, 0, size.width, size.height, false);
    g.fill3DRect(3, 3, size.width - 6, size.height - 6, true);

    // draw text
    FontMetrics metrics = g.getFontMetrics();
    int centerX = size.width / 2;
    int centerY = size.height / 2;
    int textX = centerX - (metrics.stringWidth(labelString) / 2);
    int textY = centerY
            + ((metrics.getMaxAscent() + metrics.getMaxDescent()) / 2);
    g.setColor(getForeground());
    g.drawString(labelString, textX, textY);

    g.setColor(oldColor);
}
 
Example 6
private void refreshLayout() {
    final Container content = getContentPane();
    content.removeAll();
    final int titleHeight = title.getFontMetrics(body.getFont()).getMaxAscent();
    content.add(title, "h " + (titleHeight + 4) + "!");

    final String bodyText = body.getText();
    final String plainText = bodyText.replace("<html>", "").replace("</html>", "").replace("<br>", "");
    body.setText(plainText);
    final FontMetrics fontMetrics = body.getFontMetrics(body.getFont());
    body.setText(bodyText);

    final int maxWidth = 380;
    final String[] lineText = bodyText.replace("<html>", "").replace("</html>", "").trim().split("\r\n|\r|\n|<br>");
    int totalLines = 0;
    int totalWidth = 0;
    for (String text : lineText) {
        totalLines++;
        final int textWidth = fontMetrics.stringWidth(text.trim().isEmpty() ? "." : text);
        double calc1 = textWidth / ((double) maxWidth);
        final double calc2 = Math.ceil(calc1);
        long calc3 = Math.round(calc2);
        final int textLines = (int) (textWidth == 0 ? 1 : calc3 - 1);
        totalLines += textLines;
        final int W = textWidth > maxWidth ? maxWidth : textWidth;
        if (W > totalWidth) {
            totalWidth = W;
        }
    }

    final int lineHeight = fontMetrics.getMaxAscent() + fontMetrics.getMaxDescent();
    final int totalHeight = (totalLines + 1) * lineHeight;

    body.setMinimumSize(new Dimension(0, 0));
    body.setPreferredSize(new Dimension(totalWidth, totalHeight));
    body.setMaximumSize(new Dimension(maxWidth, totalHeight));

    content.add(body, "w 0:" + totalWidth + ":" + maxWidth + ", h " + totalHeight + "!");
    revalidate();
}
 
Example 7
private void calcFontMetrics( Graphics2D g2d, int w, int h ) {
    FontMetrics fm;
    Graphics2D g2 = (Graphics2D)g2d.create();

    /// ABP
    if ( g2Transform != NONE && textToUse != FILE_TEXT ) {
        g2.setFont( g2.getFont().deriveFont( getAffineTransform( g2Transform )) );
        fm = g2.getFontMetrics();
    }
    else {
        fm = g2.getFontMetrics();
    }

    maxAscent = fm.getMaxAscent();
    maxDescent = fm.getMaxDescent();
    if (maxAscent == 0) maxAscent = 10;
    if (maxDescent == 0) maxDescent = 5;
    if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
        /// Give slight extra room for each character
        maxAscent += 3;
        maxDescent += 3;
        gridWidth = fm.getMaxAdvance() + 6;
        gridHeight = maxAscent + maxDescent;
        if ( force16Cols )
          numCharAcross = 16;
        else
          numCharAcross = ( w - 10 ) / gridWidth;
        numCharDown = ( h - 10 ) / gridHeight;

        canvasInset_X = ( w - numCharAcross * gridWidth ) / 2;
        canvasInset_Y = ( h - numCharDown * gridHeight ) / 2;
        if ( numCharDown == 0 || numCharAcross == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );

        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() * numCharAcross );
    }
    else {
        maxDescent += fm.getLeading();
        canvasInset_X = 5;
        canvasInset_Y = 5;
        /// gridWidth and numCharAcross will not be used in this mode...
        gridHeight = maxAscent + maxDescent;
        numCharDown = ( h - canvasInset_Y * 2 ) / gridHeight;

        if ( numCharDown == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );
        /// If this is text loaded from file, prepares the LineBreak'ed
        /// text layout at this point
        if ( textToUse == FILE_TEXT ) {
            if ( !isPrinting )
              f2dt.fireChangeStatus( "LineBreaking Text... Please Wait", false );
            lineBreakTLs = new Vector();
            for ( int i = 0; i < fileText.length; i++ ) {
                AttributedString as =
                  new AttributedString( fileText[i], g2.getFont().getAttributes() );

                LineBreakMeasurer lbm =
                  new LineBreakMeasurer( as.getIterator(), g2.getFontRenderContext() );

                while ( lbm.getPosition() < fileText[i].length() )
                  lineBreakTLs.add( lbm.nextLayout( (float) w ));

            }
        }
        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() );
    }
}
 
Example 8
private void calcFontMetrics( Graphics2D g2d, int w, int h ) {
    FontMetrics fm;
    Graphics2D g2 = (Graphics2D)g2d.create();

    /// ABP
    if ( g2Transform != NONE && textToUse != FILE_TEXT ) {
        g2.setFont( g2.getFont().deriveFont( getAffineTransform( g2Transform )) );
        fm = g2.getFontMetrics();
    }
    else {
        fm = g2.getFontMetrics();
    }

    maxAscent = fm.getMaxAscent();
    maxDescent = fm.getMaxDescent();
    if (maxAscent == 0) maxAscent = 10;
    if (maxDescent == 0) maxDescent = 5;
    if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
        /// Give slight extra room for each character
        maxAscent += 3;
        maxDescent += 3;
        gridWidth = fm.getMaxAdvance() + 6;
        gridHeight = maxAscent + maxDescent;
        if ( force16Cols )
          numCharAcross = 16;
        else
          numCharAcross = ( w - 10 ) / gridWidth;
        numCharDown = ( h - 10 ) / gridHeight;

        canvasInset_X = ( w - numCharAcross * gridWidth ) / 2;
        canvasInset_Y = ( h - numCharDown * gridHeight ) / 2;
        if ( numCharDown == 0 || numCharAcross == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );

        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() * numCharAcross );
    }
    else {
        maxDescent += fm.getLeading();
        canvasInset_X = 5;
        canvasInset_Y = 5;
        /// gridWidth and numCharAcross will not be used in this mode...
        gridHeight = maxAscent + maxDescent;
        numCharDown = ( h - canvasInset_Y * 2 ) / gridHeight;

        if ( numCharDown == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );
        /// If this is text loaded from file, prepares the LineBreak'ed
        /// text layout at this point
        if ( textToUse == FILE_TEXT ) {
            if ( !isPrinting )
              f2dt.fireChangeStatus( "LineBreaking Text... Please Wait", false );
            lineBreakTLs = new Vector();
            for ( int i = 0; i < fileText.length; i++ ) {
                AttributedString as =
                  new AttributedString( fileText[i], g2.getFont().getAttributes() );

                LineBreakMeasurer lbm =
                  new LineBreakMeasurer( as.getIterator(), g2.getFontRenderContext() );

                while ( lbm.getPosition() < fileText[i].length() )
                  lineBreakTLs.add( lbm.nextLayout( (float) w ));

            }
        }
        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() );
    }
}
 
Example 9
private void calcFontMetrics( Graphics2D g2d, int w, int h ) {
    FontMetrics fm;
    Graphics2D g2 = (Graphics2D)g2d.create();

    /// ABP
    if ( g2Transform != NONE && textToUse != FILE_TEXT ) {
        g2.setFont( g2.getFont().deriveFont( getAffineTransform( g2Transform )) );
        fm = g2.getFontMetrics();
    }
    else {
        fm = g2.getFontMetrics();
    }

    maxAscent = fm.getMaxAscent();
    maxDescent = fm.getMaxDescent();
    if (maxAscent == 0) maxAscent = 10;
    if (maxDescent == 0) maxDescent = 5;
    if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
        /// Give slight extra room for each character
        maxAscent += 3;
        maxDescent += 3;
        gridWidth = fm.getMaxAdvance() + 6;
        gridHeight = maxAscent + maxDescent;
        if ( force16Cols )
          numCharAcross = 16;
        else
          numCharAcross = ( w - 10 ) / gridWidth;
        numCharDown = ( h - 10 ) / gridHeight;

        canvasInset_X = ( w - numCharAcross * gridWidth ) / 2;
        canvasInset_Y = ( h - numCharDown * gridHeight ) / 2;
        if ( numCharDown == 0 || numCharAcross == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );

        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() * numCharAcross );
    }
    else {
        maxDescent += fm.getLeading();
        canvasInset_X = 5;
        canvasInset_Y = 5;
        /// gridWidth and numCharAcross will not be used in this mode...
        gridHeight = maxAscent + maxDescent;
        numCharDown = ( h - canvasInset_Y * 2 ) / gridHeight;

        if ( numCharDown == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );
        /// If this is text loaded from file, prepares the LineBreak'ed
        /// text layout at this point
        if ( textToUse == FILE_TEXT ) {
            if ( !isPrinting )
              f2dt.fireChangeStatus( "LineBreaking Text... Please Wait", false );
            lineBreakTLs = new Vector();
            for ( int i = 0; i < fileText.length; i++ ) {
                AttributedString as =
                  new AttributedString( fileText[i], g2.getFont().getAttributes() );

                LineBreakMeasurer lbm =
                  new LineBreakMeasurer( as.getIterator(), g2.getFontRenderContext() );

                while ( lbm.getPosition() < fileText[i].length() )
                  lineBreakTLs.add( lbm.nextLayout( (float) w ));

            }
        }
        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() );
    }
}
 
Example 10
private static BufferedImage createTextImage(final SignatureImageTextParameters textParameters, final Font font, final Dimension dimension) {
	String[] lines = textParameters.getText().split("\n");

	int imageType;
	if (isTransparent(textParameters.getTextColor(), textParameters.getBackgroundColor())) {
		LOG.warn("Transparency detected and enabled (Be aware: not valid with PDF/A !)");
		imageType = BufferedImage.TYPE_INT_ARGB;
	} else {
		imageType = BufferedImage.TYPE_INT_RGB;
	}

	BufferedImage img = new BufferedImage(dimension.width, dimension.height, imageType);
	Graphics2D g = img.createGraphics();
	g.setFont(font);
	FontMetrics fm = g.getFontMetrics(font);

	// Improve text rendering
	CommonDrawerUtils.initRendering(g);

	if (textParameters.getBackgroundColor() == null) {
		g.setColor(Color.WHITE);
	} else {
		g.setColor(textParameters.getBackgroundColor());
	}
	g.fillRect(0, 0, dimension.width, dimension.height);

	if (textParameters.getTextColor() == null) {
		g.setPaint(Color.BLACK);
	} else {
		g.setPaint(textParameters.getTextColor());
	}

	int lineHeight = fm.getHeight();
	float y = fm.getMaxAscent() + textParameters.getPadding();

	for (String line : lines) {
		float x = textParameters.getPadding(); // left alignment
		if (textParameters.getSignerTextHorizontalAlignment() != null) {
			switch (textParameters.getSignerTextHorizontalAlignment()) {
				case RIGHT:
					x = img.getWidth() - fm.stringWidth(line) - x; // -x because of margin
					break;
				case CENTER:
					x = (float)(img.getWidth() - fm.stringWidth(line)) / 2;
					break;
				case LEFT:
				default:
					// nothing
					break;
			}
		}
		g.drawString(line, x, y);
		y += lineHeight;
	}
	g.dispose();

	return img;
}
 
Example 11
private void calcFontMetrics( Graphics2D g2d, int w, int h ) {
    FontMetrics fm;
    Graphics2D g2 = (Graphics2D)g2d.create();

    /// ABP
    if ( g2Transform != NONE && textToUse != FILE_TEXT ) {
        g2.setFont( g2.getFont().deriveFont( getAffineTransform( g2Transform )) );
        fm = g2.getFontMetrics();
    }
    else {
        fm = g2.getFontMetrics();
    }

    maxAscent = fm.getMaxAscent();
    maxDescent = fm.getMaxDescent();
    if (maxAscent == 0) maxAscent = 10;
    if (maxDescent == 0) maxDescent = 5;
    if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
        /// Give slight extra room for each character
        maxAscent += 3;
        maxDescent += 3;
        gridWidth = fm.getMaxAdvance() + 6;
        gridHeight = maxAscent + maxDescent;
        if ( force16Cols )
          numCharAcross = 16;
        else
          numCharAcross = ( w - 10 ) / gridWidth;
        numCharDown = ( h - 10 ) / gridHeight;

        canvasInset_X = ( w - numCharAcross * gridWidth ) / 2;
        canvasInset_Y = ( h - numCharDown * gridHeight ) / 2;
        if ( numCharDown == 0 || numCharAcross == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );

        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() * numCharAcross );
    }
    else {
        maxDescent += fm.getLeading();
        canvasInset_X = 5;
        canvasInset_Y = 5;
        /// gridWidth and numCharAcross will not be used in this mode...
        gridHeight = maxAscent + maxDescent;
        numCharDown = ( h - canvasInset_Y * 2 ) / gridHeight;

        if ( numCharDown == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );
        /// If this is text loaded from file, prepares the LineBreak'ed
        /// text layout at this point
        if ( textToUse == FILE_TEXT ) {
            if ( !isPrinting )
              f2dt.fireChangeStatus( "LineBreaking Text... Please Wait", false );
            lineBreakTLs = new Vector();
            for ( int i = 0; i < fileText.length; i++ ) {
                AttributedString as =
                  new AttributedString( fileText[i], g2.getFont().getAttributes() );

                LineBreakMeasurer lbm =
                  new LineBreakMeasurer( as.getIterator(), g2.getFontRenderContext() );

                while ( lbm.getPosition() < fileText[i].length() )
                  lineBreakTLs.add( lbm.nextLayout( (float) w ));

            }
        }
        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() );
    }
}
 
Example 12
private void calcFontMetrics( Graphics2D g2d, int w, int h ) {
    FontMetrics fm;
    Graphics2D g2 = (Graphics2D)g2d.create();

    /// ABP
    if ( g2Transform != NONE && textToUse != FILE_TEXT ) {
        g2.setFont( g2.getFont().deriveFont( getAffineTransform( g2Transform )) );
        fm = g2.getFontMetrics();
    }
    else {
        fm = g2.getFontMetrics();
    }

    maxAscent = fm.getMaxAscent();
    maxDescent = fm.getMaxDescent();
    if (maxAscent == 0) maxAscent = 10;
    if (maxDescent == 0) maxDescent = 5;
    if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
        /// Give slight extra room for each character
        maxAscent += 3;
        maxDescent += 3;
        gridWidth = fm.getMaxAdvance() + 6;
        gridHeight = maxAscent + maxDescent;
        if ( force16Cols )
          numCharAcross = 16;
        else
          numCharAcross = ( w - 10 ) / gridWidth;
        numCharDown = ( h - 10 ) / gridHeight;

        canvasInset_X = ( w - numCharAcross * gridWidth ) / 2;
        canvasInset_Y = ( h - numCharDown * gridHeight ) / 2;
        if ( numCharDown == 0 || numCharAcross == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );

        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() * numCharAcross );
    }
    else {
        maxDescent += fm.getLeading();
        canvasInset_X = 5;
        canvasInset_Y = 5;
        /// gridWidth and numCharAcross will not be used in this mode...
        gridHeight = maxAscent + maxDescent;
        numCharDown = ( h - canvasInset_Y * 2 ) / gridHeight;

        if ( numCharDown == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );
        /// If this is text loaded from file, prepares the LineBreak'ed
        /// text layout at this point
        if ( textToUse == FILE_TEXT ) {
            if ( !isPrinting )
              f2dt.fireChangeStatus( "LineBreaking Text... Please Wait", false );
            lineBreakTLs = new Vector();
            for ( int i = 0; i < fileText.length; i++ ) {
                AttributedString as =
                  new AttributedString( fileText[i], g2.getFont().getAttributes() );

                LineBreakMeasurer lbm =
                  new LineBreakMeasurer( as.getIterator(), g2.getFontRenderContext() );

                while ( lbm.getPosition() < fileText[i].length() )
                  lineBreakTLs.add( lbm.nextLayout( (float) w ));

            }
        }
        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() );
    }
}
 
Example 13
/** Paints the icon and text using the HTML mini renderer */
protected final void paintIconAndText (Graphics2D g, BasicSlidingTabDisplayerUI.IndexButton b, Object orientation) {
    FontMetrics fm = g.getFontMetrics(b.getFont());
    Insets ins = b.getInsets();
    
    boolean flip = orientation == TabDisplayer.ORIENTATION_EAST || 
        orientation == TabDisplayer.ORIENTATION_WEST;
    
    int txtX = flip ? ins.top : ins.left;
    
    int txtY = orientation == TabDisplayer.ORIENTATION_EAST ? ins.right :
        orientation == TabDisplayer.ORIENTATION_WEST ? ins.left : ins.top;
        
    int txtW = flip ? b.getHeight() - (ins.top + ins.bottom): 
        b.getWidth() - (ins.left + ins.right);
    
    int iconX = txtX;
    int iconY = txtY;
    
    int txtH = fm.getHeight();
    txtY += fm.getMaxAscent();
    
    Icon icon = b.getIcon();
    
    int iconH = icon.getIconHeight();
    int iconW = icon.getIconWidth();

    int workingHeight;
    if (flip) {
        workingHeight = b.getWidth() - (ins.left + ins.right);
    } else {
        workingHeight = b.getHeight() - (ins.top + ins.bottom);
    }
    txtY += (workingHeight / 2) - (txtH / 2);
    iconY += (workingHeight / 2) - (iconH / 2);
    
    if (icon != null && iconW > 0 && iconH > 0) {
        txtX += iconW + b.getIconTextGap();
        icon.paintIcon (b, g, iconX, iconY);
        txtW -= iconH + b.getIconTextGap();
    }
    
    HtmlRenderer.renderString(b.getText(), g, txtX, txtY, txtW, txtH, b.getFont(),
          b.getForeground(), HtmlRenderer.STYLE_TRUNCATE, true);
}
 
Example 14
Source Project: netbeans   File: HtmlLabelUI.java    License: Apache License 2.0 4 votes vote down vote up
private Dimension calcPreferredSize(HtmlRendererImpl r) {
    Insets ins = r.getInsets();
    Dimension prefSize = new java.awt.Dimension(ins.left + ins.right, ins.top + ins.bottom);
    String text = r.getText();

    Graphics g = r.getGraphics();
    Icon icon = r.getIcon();
    Font font = font(r);
    if (text != null) {
        FontMetrics fm = g.getFontMetrics(font);
        prefSize.height += (fm.getMaxAscent() + fm.getMaxDescent());
    }

    if (icon != null) {
        if (r.isCentered()) {
            prefSize.height += (icon.getIconHeight() + r.getIconTextGap());
            prefSize.width += icon.getIconWidth();
        } else {
            prefSize.height = Math.max(icon.getIconHeight() + ins.top + ins.bottom, prefSize.height);
            prefSize.width += (icon.getIconWidth() + r.getIconTextGap());
        }
    }
    
    //Antialiasing affects the text metrics, so use it if needed when
    //calculating preferred size or the result here will be narrower
    //than the space actually needed
    ((Graphics2D) g).addRenderingHints(getHints());

    int textwidth = textWidth(text, g, font, r.isHtml()) + 4;

    if (r.isCentered()) {
        prefSize.width = Math.max(prefSize.width, textwidth + ins.right + ins.left);
    } else {
        prefSize.width += (textwidth + r.getIndent());
    }

    if (FIXED_HEIGHT > 0) {
        prefSize.height = FIXED_HEIGHT;
    }

    return prefSize;
}
 
Example 15
Source Project: netbeans   File: HtmlLabelUI.java    License: Apache License 2.0 4 votes vote down vote up
/** Actually paint the icon and text using our own html rendering engine. */
private void paintIconAndText(Graphics g, HtmlRendererImpl r) {
    Font f = font(r);
    g.setFont(f);

    FontMetrics fm = g.getFontMetrics();

    //Find out what height we need
    int txtH = fm.getMaxAscent() + fm.getMaxDescent();
    Insets ins = r.getInsets();

    //find out the available height less the insets
    int rHeight = r.getHeight();
    int availH = rHeight - (ins.top + ins.bottom);

    int txtY;

    if (availH >= txtH) {
        //Center the text if we have space
        txtY = (txtH + ins.top + ((availH / 2) - (txtH / 2))) - fm.getMaxDescent();
    } else if (r.getHeight() > txtH) {
        txtY = txtH + (rHeight - txtH) / 2 - fm.getMaxDescent();
    } else {
        //Okay, it's not going to fit, punt.
        txtY = fm.getMaxAscent();
    }
    
    int txtX = r.getIndent();

    Icon icon = r.getIcon();

    //Check the icon non-null and height (see TabData.NO_ICON for why)
    if ((icon != null) && (icon.getIconWidth() > 0) && (icon.getIconHeight() > 0)) {
        int iconY;

        if (availH > icon.getIconHeight()) {
            //add 2 to make sure icon top pixels are not cut off by outline
            iconY = ins.top + ((availH / 2) - (icon.getIconHeight() / 2)); // + 2;
        } else if (availH == icon.getIconHeight()) {
            //They're an exact match, make it 0
            iconY = ins.top;
        } else {
            //Won't fit; make the top visible and cut the rest off (option:
            //center it and clip it on top and bottom - probably even harder
            //to recognize that way, though)
            iconY = ins.top;
        }

        //add in the insets
        int iconX = ins.left + r.getIndent() + 1; //+1 to get it out of the way of the focus border

        try {
            //Diagnostic - the CPP module currently is constructing
            //some ImageIcon from a null image in Options.  So, catch it and at
            //least give a meaningful message that indicates what node
            //is the culprit
            icon.paintIcon(r, g, iconX, iconY);
        } catch (NullPointerException npe) {
            Exceptions.attachMessage(npe,
                                     "Probably an ImageIcon with a null source image: " +
                                     icon + " - " + r.getText()); //NOI18N
            Exceptions.printStackTrace(npe);
        }

        txtX = iconX + icon.getIconWidth() + r.getIconTextGap();
    } else {
        //If there's no icon, paint the text where the icon would start
        txtX += ins.left;
    }

    String text = r.getText();

    if (text == null) {
        //No text, we're done
        return;
    }

    //Get the available horizontal pixels for text
    int txtW = (icon != null)
        ? (r.getWidth() - (ins.left + ins.right + icon.getIconWidth() + r.getIconTextGap() + r.getIndent()))
        : (r.getWidth() - (ins.left + ins.right + r.getIndent()));

    Color background = getBackgroundFor(r);
    Color foreground = ensureContrastingColor(getForegroundFor(r), background);

    if (r.isHtml()) {
        HtmlRenderer._renderHTML(text, 0, g, txtX, txtY, txtW, txtH, f, foreground, r.getRenderStyle(), true, background, r.isSelected());
    } else {
        HtmlRenderer.renderPlainString(text, g, txtX, txtY, txtW, txtH, f, foreground, r.getRenderStyle(), true);
    }
}
 
Example 16
@Override
protected void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
    
    ButtonModel m = getModel();
    Insets insets = getInsets();
    
    int width = getWidth() - insets.left - insets.right;
    int height = getHeight() - insets.top - insets.bottom;
    
    tileStretchPaint(g2,this,(BufferedImage) getImage(m.isArmed()), sourceInsets);
    
    if (getModel().isRollover()) {
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(buttonHighlight,
                insets.left + 2, insets.top + 2,
                width - 4, height - 4, null);
    }
    
    FontMetrics fm = getFontMetrics(getFont());
    TextLayout layout = new TextLayout(getText(),
            getFont(),
            g2.getFontRenderContext());
    Rectangle2D bounds = layout.getBounds();
    
    int x = (int) (getWidth() - insets.left - insets.right -
            bounds.getWidth()) / 2;
    //x -= 2;
    int y = (getHeight() - insets.top - insets.bottom -
             fm.getMaxAscent() - fm.getMaxDescent()) / 2;
    y += fm.getAscent() - 1;
    
    if (m.isArmed()) {
        x += 1;
        y += 1;
    }
    
    g2.setColor(shadowColor);
    layout.draw(g2,
            x + (int) Math.ceil(shadowOffsetX),
            y + (int) Math.ceil(shadowOffsetY));
    g2.setColor(getForeground());
    layout.draw(g2, x, y);
}
 
Example 17
private void calcFontMetrics( Graphics2D g2d, int w, int h ) {
    FontMetrics fm;
    Graphics2D g2 = (Graphics2D)g2d.create();

    /// ABP
    if ( g2Transform != NONE && textToUse != FILE_TEXT ) {
        g2.setFont( g2.getFont().deriveFont( getAffineTransform( g2Transform )) );
        fm = g2.getFontMetrics();
    }
    else {
        fm = g2.getFontMetrics();
    }

    maxAscent = fm.getMaxAscent();
    maxDescent = fm.getMaxDescent();
    if (maxAscent == 0) maxAscent = 10;
    if (maxDescent == 0) maxDescent = 5;
    if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
        /// Give slight extra room for each character
        maxAscent += 3;
        maxDescent += 3;
        gridWidth = fm.getMaxAdvance() + 6;
        gridHeight = maxAscent + maxDescent;
        if ( force16Cols )
          numCharAcross = 16;
        else
          numCharAcross = ( w - 10 ) / gridWidth;
        numCharDown = ( h - 10 ) / gridHeight;

        canvasInset_X = ( w - numCharAcross * gridWidth ) / 2;
        canvasInset_Y = ( h - numCharDown * gridHeight ) / 2;
        if ( numCharDown == 0 || numCharAcross == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );

        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() * numCharAcross );
    }
    else {
        maxDescent += fm.getLeading();
        canvasInset_X = 5;
        canvasInset_Y = 5;
        /// gridWidth and numCharAcross will not be used in this mode...
        gridHeight = maxAscent + maxDescent;
        numCharDown = ( h - canvasInset_Y * 2 ) / gridHeight;

        if ( numCharDown == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );
        /// If this is text loaded from file, prepares the LineBreak'ed
        /// text layout at this point
        if ( textToUse == FILE_TEXT ) {
            if ( !isPrinting )
              f2dt.fireChangeStatus( "LineBreaking Text... Please Wait", false );
            lineBreakTLs = new Vector();
            for ( int i = 0; i < fileText.length; i++ ) {
                AttributedString as =
                  new AttributedString( fileText[i], g2.getFont().getAttributes() );

                LineBreakMeasurer lbm =
                  new LineBreakMeasurer( as.getIterator(), g2.getFontRenderContext() );

                while ( lbm.getPosition() < fileText[i].length() )
                  lineBreakTLs.add( lbm.nextLayout( (float) w ));

            }
        }
        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() );
    }
}
 
Example 18
/**
 * Create a string image.
 *
 * @param text The {@code String} to make an image of.
 * @param color The {@code Color} to use for the text.
 * @param font The {@code Font} to display the text with.
 * @param fm The {@code FontMetrics} to use with the font.
 * @return The image that was created.
 */
private BufferedImage createStringImage(String text, Color color,
                                        Font font, FontMetrics fm) {
    final int width = fm.stringWidth(text) + 4;
    final int height = fm.getMaxAscent() + fm.getMaxDescent();
    BufferedImage img = new BufferedImage(width, height,
                                          BufferedImage.TYPE_INT_ARGB);
    // draw the string with selected color
    Graphics2D g = img.createGraphics();
    g.setColor(makeStringBorderColor(color));
    g.setFont(font);
    g.drawString(text, 2, fm.getMaxAscent());

    // draw the border around letters
    int borderWidth = 1;
    int borderColor = makeStringBorderColor(color).getRGB();
    int srcRGB, dstRGB, srcA;
    for (int biY = 0; biY < height; biY++) {
        for (int biX = borderWidth; biX < width - borderWidth; biX++) {
            int biXI = width - biX - 1;
            for (int d = 1; d <= borderWidth; d++) {
                // left to right
                srcRGB = img.getRGB(biX, biY);
                srcA = (srcRGB >> 24) & 0xFF;
                dstRGB = img.getRGB(biX - d, biY);
                if (dstRGB != borderColor) {
                    if (srcA > 0) {
                        img.setRGB(biX, biY, borderColor);
                        img.setRGB(biX - d, biY, srcRGB);
                    }
                }
                // right to left
                srcRGB = img.getRGB(biXI, biY);
                srcA = (srcRGB >> 24) & 0xFF;
                dstRGB = img.getRGB(biXI + d, biY);
                if (dstRGB != borderColor) {
                    if (srcA > 0) {
                        img.setRGB(biXI, biY, borderColor);
                        img.setRGB(biXI + d, biY, srcRGB);
                    }
                }
            }
        }
    }
    for (int biX = 0; biX < width; biX++) {
        for (int biY = borderWidth; biY < height - borderWidth; biY++) {
            int biYI = height - biY - 1;
            for (int d = 1; d <= borderWidth; d++) {
                // top to bottom
                srcRGB = img.getRGB(biX, biY);
                srcA = (srcRGB >> 24) & 0xFF;
                dstRGB = img.getRGB(biX, biY - d);
                if (dstRGB != borderColor) {
                    if (srcA > 0) {
                        img.setRGB(biX, biY, borderColor);
                        img.setRGB(biX, biY - d, srcRGB);
                    }
                }
                // bottom to top
                srcRGB = img.getRGB(biX, biYI);
                srcA = (srcRGB >> 24) & 0xFF;
                dstRGB = img.getRGB(biX, biYI + d);
                if (dstRGB != borderColor) {
                    if (srcA > 0) {
                        img.setRGB(biX, biYI, borderColor);
                        img.setRGB(biX, biYI + d, srcRGB);
                    }
                }
            }
        }
    }

    g.setColor(color);
    g.drawString(text, 2, fm.getMaxAscent());
    g.dispose();
    return img;
}
 
Example 19
private void calcFontMetrics( Graphics2D g2d, int w, int h ) {
    FontMetrics fm;
    Graphics2D g2 = (Graphics2D)g2d.create();

    /// ABP
    if ( g2Transform != NONE && textToUse != FILE_TEXT ) {
        g2.setFont( g2.getFont().deriveFont( getAffineTransform( g2Transform )) );
        fm = g2.getFontMetrics();
    }
    else {
        fm = g2.getFontMetrics();
    }

    maxAscent = fm.getMaxAscent();
    maxDescent = fm.getMaxDescent();
    if (maxAscent == 0) maxAscent = 10;
    if (maxDescent == 0) maxDescent = 5;
    if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
        /// Give slight extra room for each character
        maxAscent += 3;
        maxDescent += 3;
        gridWidth = fm.getMaxAdvance() + 6;
        gridHeight = maxAscent + maxDescent;
        if ( force16Cols )
          numCharAcross = 16;
        else
          numCharAcross = ( w - 10 ) / gridWidth;
        numCharDown = ( h - 10 ) / gridHeight;

        canvasInset_X = ( w - numCharAcross * gridWidth ) / 2;
        canvasInset_Y = ( h - numCharDown * gridHeight ) / 2;
        if ( numCharDown == 0 || numCharAcross == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );

        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() * numCharAcross );
    }
    else {
        maxDescent += fm.getLeading();
        canvasInset_X = 5;
        canvasInset_Y = 5;
        /// gridWidth and numCharAcross will not be used in this mode...
        gridHeight = maxAscent + maxDescent;
        numCharDown = ( h - canvasInset_Y * 2 ) / gridHeight;

        if ( numCharDown == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );
        /// If this is text loaded from file, prepares the LineBreak'ed
        /// text layout at this point
        if ( textToUse == FILE_TEXT ) {
            if ( !isPrinting )
              f2dt.fireChangeStatus( "LineBreaking Text... Please Wait", false );
            lineBreakTLs = new Vector();
            for ( int i = 0; i < fileText.length; i++ ) {
                AttributedString as =
                  new AttributedString( fileText[i], g2.getFont().getAttributes() );

                LineBreakMeasurer lbm =
                  new LineBreakMeasurer( as.getIterator(), g2.getFontRenderContext() );

                while ( lbm.getPosition() < fileText[i].length() )
                  lineBreakTLs.add( lbm.nextLayout( (float) w ));

            }
        }
        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() );
    }
}
 
Example 20
private void calcFontMetrics( Graphics2D g2d, int w, int h ) {
    FontMetrics fm;
    Graphics2D g2 = (Graphics2D)g2d.create();

    /// ABP
    if ( g2Transform != NONE && textToUse != FILE_TEXT ) {
        g2.setFont( g2.getFont().deriveFont( getAffineTransform( g2Transform )) );
        fm = g2.getFontMetrics();
    }
    else {
        fm = g2.getFontMetrics();
    }

    maxAscent = fm.getMaxAscent();
    maxDescent = fm.getMaxDescent();
    if (maxAscent == 0) maxAscent = 10;
    if (maxDescent == 0) maxDescent = 5;
    if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
        /// Give slight extra room for each character
        maxAscent += 3;
        maxDescent += 3;
        gridWidth = fm.getMaxAdvance() + 6;
        gridHeight = maxAscent + maxDescent;
        if ( force16Cols )
          numCharAcross = 16;
        else
          numCharAcross = ( w - 10 ) / gridWidth;
        numCharDown = ( h - 10 ) / gridHeight;

        canvasInset_X = ( w - numCharAcross * gridWidth ) / 2;
        canvasInset_Y = ( h - numCharDown * gridHeight ) / 2;
        if ( numCharDown == 0 || numCharAcross == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );

        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() * numCharAcross );
    }
    else {
        maxDescent += fm.getLeading();
        canvasInset_X = 5;
        canvasInset_Y = 5;
        /// gridWidth and numCharAcross will not be used in this mode...
        gridHeight = maxAscent + maxDescent;
        numCharDown = ( h - canvasInset_Y * 2 ) / gridHeight;

        if ( numCharDown == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );
        /// If this is text loaded from file, prepares the LineBreak'ed
        /// text layout at this point
        if ( textToUse == FILE_TEXT ) {
            if ( !isPrinting )
              f2dt.fireChangeStatus( "LineBreaking Text... Please Wait", false );
            lineBreakTLs = new Vector();
            for ( int i = 0; i < fileText.length; i++ ) {
                AttributedString as =
                  new AttributedString( fileText[i], g2.getFont().getAttributes() );

                LineBreakMeasurer lbm =
                  new LineBreakMeasurer( as.getIterator(), g2.getFontRenderContext() );

                while ( lbm.getPosition() < fileText[i].length() )
                  lineBreakTLs.add( lbm.nextLayout( (float) w ));

            }
        }
        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() );
    }
}