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

The following examples show how to use java.awt.FontMetrics#getAscent() . 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 File: MotifBorders.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Reinitialize the insets parameter with this Border's current Insets.
 * @param c the component for which this border insets value applies
 * @param insets the object to be reinitialized
 */
public Insets getBorderInsets(Component c, Insets insets) {
    if (!(c instanceof JPopupMenu)) {
        return insets;
    }
    FontMetrics fm;
    int         descent = 0;
    int         ascent = 16;

    String title = ((JPopupMenu)c).getLabel();
    if (title == null) {
        insets.left = insets.top = insets.right = insets.bottom = 0;
        return insets;
    }

    fm = c.getFontMetrics(font);

    if(fm != null) {
        descent = fm.getDescent();
        ascent = fm.getAscent();
    }

    insets.top += ascent + descent + TEXT_SPACING + GROOVE_HEIGHT;
    return insets;
}
 
Example 2
Source File: UnicodeFont.java    From slick2d-maven with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Initialise the font to be used based on configuration
 * 
 * @param baseFont The AWT font to render
 * @param size The point size of the font to generated
 * @param bold True if the font should be rendered in bold typeface
 * @param italic True if the font should be rendered in bold typeface
 */
private void initializeFont(Font baseFont, int size, boolean bold, boolean italic) {
	Map attributes = baseFont.getAttributes();
	attributes.put(TextAttribute.SIZE, new Float(size));
	attributes.put(TextAttribute.WEIGHT, bold ? TextAttribute.WEIGHT_BOLD : TextAttribute.WEIGHT_REGULAR);
	attributes.put(TextAttribute.POSTURE, italic ? TextAttribute.POSTURE_OBLIQUE : TextAttribute.POSTURE_REGULAR);
	try {
		attributes.put(TextAttribute.class.getDeclaredField("KERNING").get(null), TextAttribute.class.getDeclaredField(
			"KERNING_ON").get(null));
	} catch (Exception ignored) {
	}
	font = baseFont.deriveFont(attributes);

	FontMetrics metrics = GlyphPage.getScratchGraphics().getFontMetrics(font);
	ascent = metrics.getAscent();
	descent = metrics.getDescent();
	leading = metrics.getLeading();
	
	// Determine width of space glyph (getGlyphPixelBounds gives a width of zero).
	char[] chars = " ".toCharArray();
	GlyphVector vector = font.layoutGlyphVector(GlyphPage.renderContext, chars, 0, chars.length, Font.LAYOUT_LEFT_TO_RIGHT);
	spaceWidth = vector.getGlyphLogicalBounds(0).getBounds().width;
}
 
Example 3
Source File: TextUtilities.java    From ccu-historian with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns the bounds for the specified text.
 *
 * @param text  the text (<code>null</code> permitted).
 * @param g2  the graphics context (not <code>null</code>).
 * @param fm  the font metrics (not <code>null</code>).
 *
 * @return The text bounds (<code>null</code> if the <code>text</code>
 *         argument is <code>null</code>).
 */
public static Rectangle2D getTextBounds(String text, Graphics2D g2, 
        FontMetrics fm) {

    Rectangle2D bounds;
    if (TextUtilities.useFontMetricsGetStringBounds) {
        bounds = fm.getStringBounds(text, g2);
        // getStringBounds() can return incorrect height for some Unicode
        // characters...see bug parade 6183356, let's replace it with
        // something correct
        LineMetrics lm = fm.getFont().getLineMetrics(text,
                g2.getFontRenderContext());
        bounds.setRect(bounds.getX(), bounds.getY(), bounds.getWidth(),
                lm.getHeight());
    }
    else {
        double width = fm.stringWidth(text);
        double height = fm.getHeight();
        if (logger.isDebugEnabled()) {
            logger.debug("Height = " + height);
        }
        bounds = new Rectangle2D.Double(0.0, -fm.getAscent(), width,
                height);
    }
    return bounds;
}
 
Example 4
Source File: MotifBorders.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Reinitialize the insets parameter with this Border's current Insets.
 * @param c the component for which this border insets value applies
 * @param insets the object to be reinitialized
 */
public Insets getBorderInsets(Component c, Insets insets) {
    if (!(c instanceof JPopupMenu)) {
        return insets;
    }
    FontMetrics fm;
    int         descent = 0;
    int         ascent = 16;

    String title = ((JPopupMenu)c).getLabel();
    if (title == null) {
        insets.left = insets.top = insets.right = insets.bottom = 0;
        return insets;
    }

    fm = c.getFontMetrics(font);

    if(fm != null) {
        descent = fm.getDescent();
        ascent = fm.getAscent();
    }

    insets.top += ascent + descent + TEXT_SPACING + GROOVE_HEIGHT;
    return insets;
}
 
Example 5
Source File: FlatTextFieldUI.java    From FlatLaf with Apache License 2.0 6 votes vote down vote up
static void paintPlaceholder( Graphics g, JTextComponent c, Color placeholderForeground ) {
	// check whether text component is empty
	if( c.getDocument().getLength() > 0 )
		return;

	// check for JComboBox
	Container parent = c.getParent();
	JComponent jc = (parent instanceof JComboBox) ? (JComboBox<?>) parent : c;

	// get placeholder text
	Object placeholder = jc.getClientProperty( FlatClientProperties.PLACEHOLDER_TEXT );
	if( !(placeholder instanceof String) )
		return;

	// compute placeholder location
	Insets insets = c.getInsets();
	FontMetrics fm = c.getFontMetrics( c.getFont() );
	int x = insets.left;
	int y = insets.top + fm.getAscent() + ((c.getHeight() - insets.top - insets.bottom - fm.getHeight()) / 2);

	// paint placeholder
	g.setColor( placeholderForeground );
	FlatUIUtils.drawString( c, g, (String) placeholder, x, y );
}
 
Example 6
Source File: CompositionArea.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
private Rectangle getCaretRectangle(TextHitInfo caret) {
    int caretLocation = 0;
    TextLayout layout = composedTextLayout;
    if (layout != null) {
        caretLocation = Math.round(layout.getCaretInfo(caret)[0]);
    }
    Graphics g = getGraphics();
    FontMetrics metrics = null;
    try {
        metrics = g.getFontMetrics();
    } finally {
        g.dispose();
    }
    return new Rectangle(TEXT_ORIGIN_X + caretLocation,
                         TEXT_ORIGIN_Y - metrics.getAscent(),
                         0, metrics.getAscent() + metrics.getDescent());
}
 
Example 7
Source File: HeapView.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Renders the text using an optional drop shadow.
 */
private void paintText(Graphics2D g, int w, int h) {
    g.setFont(getFont());
    String text = getHeapSizeText();
    FontMetrics fm = g.getFontMetrics();
    int textWidth = fm.stringWidth(text);
    int x = (w - maxTextWidth) / 2 + (maxTextWidth - textWidth);
    int y = h / 2 + fm.getAscent() / 2 - 2;
    g.setColor(TEXT_COLOR);
    g.drawString(text, x, y);
}
 
Example 8
Source File: AbstractDirectDrawer.java    From ReactionDecoder with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 *
 * @param g
 * @param text
 * @param cX
 * @param cY
 * @return
 */
public Point2f getTextPoint(Graphics g, String text, double cX, double cY) {
    FontMetrics metrics = g.getFontMetrics();
    Rectangle2D stringBounds = metrics.getStringBounds(text, g);
    double halfWidth = stringBounds.getWidth() / 2;
    double halfHeight = stringBounds.getHeight() / 2;
    double ascent = metrics.getAscent();
    float x = (float) (cX - halfWidth);
    float y = (float) (cY - halfHeight + ascent);
    return new Point2f(x, y);
}
 
Example 9
Source File: AquaViewTabDisplayerUI.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Dimension getPreferredSize(JComponent c) {
    FontMetrics fm = getTxtFontMetrics();
    int height = fm == null ?
            21 : fm.getAscent() + 2 * fm.getDescent() + 3;
    height += 1; //align with editor tabs
    Insets insets = c.getInsets();
    prefSize.height = height + insets.bottom + insets.top;
    return prefSize;
}
 
Example 10
Source File: RotatedTextDrawable.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
private int getXPadding( final boolean fromBottom, final FontMetrics fontMetrics, final Rectangle2D bounds ) {

    if ( ElementAlignment.CENTER.equals( hAlign ) ) {
      return (int) ( bounds.getWidth() / 2 );
    }
    if ( ElementAlignment.LEFT.equals( hAlign ) || ElementAlignment.JUSTIFY.equals( hAlign ) ) {
      return fromBottom ? fontMetrics.getAscent() : fontMetrics.getDescent();
    }
    if ( ElementAlignment.RIGHT.equals( hAlign ) ) {
      return (int) ( bounds.getWidth() - ( fromBottom ? fontMetrics.getDescent() : fontMetrics.getAscent() ) );
    }

    return 0;
  }
 
Example 11
Source File: BasicLabelUI.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Paints the label text with the foreground color, if the label is opaque
 * then paints the entire background with the background color. The Label
 * text is drawn by {@link #paintEnabledText} or {@link #paintDisabledText}.
 * The locations of the label parts are computed by {@link #layoutCL}.
 *
 * @see #paintEnabledText
 * @see #paintDisabledText
 * @see #layoutCL
 */
public void paint(Graphics g, JComponent c)
{
    JLabel label = (JLabel)c;
    String text = label.getText();
    Icon icon = (label.isEnabled()) ? label.getIcon() : label.getDisabledIcon();

    if ((icon == null) && (text == null)) {
        return;
    }

    FontMetrics fm = SwingUtilities2.getFontMetrics(label, g);
    String clippedText = layout(label, fm, c.getWidth(), c.getHeight());

    if (icon != null) {
        icon.paintIcon(c, g, paintIconR.x, paintIconR.y);
    }

    if (text != null) {
        View v = (View) c.getClientProperty(BasicHTML.propertyKey);
        if (v != null) {
            v.paint(g, paintTextR);
        } else {
            int textX = paintTextR.x;
            int textY = paintTextR.y + fm.getAscent();

            if (label.isEnabled()) {
                paintEnabledText(label, g, clippedText, textX, textY);
            }
            else {
                paintDisabledText(label, g, clippedText, textX, textY);
            }
        }
    }
}
 
Example 12
Source File: CodeFoldingSideBar.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected int getMarkSize(Graphics g){
    if (g != null){
        FontMetrics fm = g.getFontMetrics(getColoring().getFont());
        if (fm != null){
            int ret = fm.getAscent() - fm.getDescent();
            return ret - ret%2;
        }
    }
    return -1;
}
 
Example 13
Source File: MetalViewTabDisplayerUI.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Dimension getPreferredSize(JComponent c) {
    FontMetrics fm = getTxtFontMetrics();
    int height = fm == null ?
            21 : fm.getAscent() + 2 * fm.getDescent() + 4;
    Insets insets = c.getInsets();
    prefSize.height = height + insets.bottom + insets.top;
    return prefSize;
}
 
Example 14
Source File: TMAbstractEdge.java    From ontopia with Apache License 2.0 5 votes vote down vote up
/**
 * @param g -
 *               The graphic context for the drawing operation.
 * @param string -
 *               The String to be rendered.
 * @param x -
 *               The x coordinate where the String should be positioned.
 * @param y -
 *               The y coordinate where the String should be positioned. NOTE: The text is <b>centered </b> over the given coordinates.
 */
protected void paintToolTipText(Graphics g, String string, int x, int y) {

  g.setFont(this.getFont());
  FontMetrics fontMetrics = g.getFontMetrics();

  int a = fontMetrics.getAscent();
  int h = a + fontMetrics.getDescent();
  int w = fontMetrics.stringWidth(string);

  int xPosition = x - (w / 2);
  int yPosition = y - (h / 2);

  // Draw the background

  Color c = this.getColor();
  g.setColor(c);

  int r = h / 2;
  int vPad = h / 8;
  int hPad = h / 4;

  g.fillRoundRect(xPosition - hPad, yPosition - vPad, w + (2 * hPad), h
      + (2 * vPad), r, r);

  //Draw a defined edge to the popup
  g.setColor(TMTopicNode.textColourForBackground(c));
  g.drawRoundRect(xPosition - hPad, yPosition - vPad, w + (2 * hPad), h
      + (2 * vPad), r, r);

  // Draw the text
  g.drawString(string, xPosition, yPosition + a);
}
 
Example 15
Source File: AboutPanel.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
private static int draw(Graphics2D gc, String text, int y, int right, boolean addGap, boolean onLeft) {
    String[]    one     = text.split("\n");
    FontMetrics fm      = gc.getFontMetrics();
    int         fHeight = fm.getAscent() + fm.getDescent();
    for (int i = one.length - 1; i >= 0; i--) {
        gc.drawString(one[i], onLeft ? HMARGIN : right - fm.stringWidth(one[i]), y);
        y -= fHeight;
    }
    if (addGap) {
        y -= fHeight / 2;
    }
    return y;
}
 
Example 16
Source File: MotifBorders.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Paints the border for the specified component with the
 * specified position and size.
 * @param c the component for which this border is being painted
 * @param g the paint graphics
 * @param x the x position of the painted border
 * @param y the y position of the painted border
 * @param width the width of the painted border
 * @param height the height of the painted border
 */
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
    if (!(c instanceof JPopupMenu)) {
        return;
    }

    Font origFont = g.getFont();
    Color origColor = g.getColor();
    JPopupMenu popup = (JPopupMenu)c;

    String title = popup.getLabel();
    if (title == null) {
        return;
    }

    g.setFont(font);

    FontMetrics fm = SwingUtilities2.getFontMetrics(popup, g, font);
    int         fontHeight = fm.getHeight();
    int         descent = fm.getDescent();
    int         ascent = fm.getAscent();
    Point       textLoc = new Point();
    int         stringWidth = SwingUtilities2.stringWidth(popup, fm,
                                                          title);

    textLoc.y = y + ascent + TEXT_SPACING;
    textLoc.x = x + ((width - stringWidth) / 2);

    g.setColor(background);
    g.fillRect(textLoc.x - TEXT_SPACING, textLoc.y - (fontHeight-descent),
               stringWidth + (2 * TEXT_SPACING), fontHeight - descent);
    g.setColor(foreground);
    SwingUtilities2.drawString(popup, g, title, textLoc.x, textLoc.y);

    MotifGraphicsUtils.drawGroove(g, x, textLoc.y + TEXT_SPACING,
                                  width, GROOVE_HEIGHT,
                                  shadowColor, highlightColor);

    g.setFont(origFont);
    g.setColor(origColor);
}
 
Example 17
Source File: LineTimeChart.java    From scelight with Apache License 2.0 4 votes vote down vote up
/**
 * Also paints the labels of the Y axis and assist lines.
 */
@Override
protected void paintAxesLabels() {
	// X (time) axis
	super.paintAxesLabels();
	
	// Y axis
	final int assistLinesCount = drawingRect.height < ASSIST_LINES_MIN_DISTANCE ? 1 : drawingRect.height / ASSIST_LINES_MIN_DISTANCE;
	final Stroke oldStroke = g.getStroke();
	g.setStroke( STROKE_DASHED );
	
	// Calculate appropriate font so value labels will fit
	Font oldFont = null;
	if ( valueMax > 9999 ) {
		// Max value is 5 digit (at least), decrease the font size
		oldFont = g.getFont();
		g.setFont( oldFont.deriveFont( 9f ) );
	} else if ( valueMax > 999 ) {
		// Max value is 4 digit (at least), decrease the font size
		oldFont = g.getFont();
		g.setFont( oldFont.deriveFont( 10f ) );
	}
	
	final FontMetrics fontMetrics = g.getFontMetrics();
	final int fontAscent = fontMetrics.getAscent();
	
	for ( int i = assistLinesCount - 1; i >= 0; i-- ) {
		final int y = drawingRect.y1 + i * drawingRect.dy / assistLinesCount; // assistLinesCount > 0
		
		g.setColor( COLOR_ASSIST_LINES );
		g.drawLine( drawingRect.x1 + 1, y, drawingRect.x2, y );
		
		g.setColor( COLOR_AXIS_LABELS );
		final String label = Integer.toString( valueMax * ( assistLinesCount - i ) / assistLinesCount );
		g.drawString( label, drawingRect.x1 - fontMetrics.stringWidth( label ) - 1, y + fontAscent / 2 - 1 );
	}
	
	if ( oldFont != null )
		g.setFont( oldFont );
	g.setStroke( oldStroke );
}
 
Example 18
Source File: LGraphics.java    From RipplePower with Apache License 2.0 4 votes vote down vote up
public void drawCenterString(String s, int x, int y) {
	FontMetrics fontmetrics = g2d.getFontMetrics();
	x -= fontmetrics.stringWidth(s) >> 1;
	y += fontmetrics.getAscent() - fontmetrics.getDescent() >> 1;
	g2d.drawString(s, x, y);
}
 
Example 19
Source File: MotifBorders.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Paints the border for the specified component with the
 * specified position and size.
 * @param c the component for which this border is being painted
 * @param g the paint graphics
 * @param x the x position of the painted border
 * @param y the y position of the painted border
 * @param width the width of the painted border
 * @param height the height of the painted border
 */
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
    if (!(c instanceof JPopupMenu)) {
        return;
    }

    Font origFont = g.getFont();
    Color origColor = g.getColor();
    JPopupMenu popup = (JPopupMenu)c;

    String title = popup.getLabel();
    if (title == null) {
        return;
    }

    g.setFont(font);

    FontMetrics fm = SwingUtilities2.getFontMetrics(popup, g, font);
    int         fontHeight = fm.getHeight();
    int         descent = fm.getDescent();
    int         ascent = fm.getAscent();
    Point       textLoc = new Point();
    int         stringWidth = SwingUtilities2.stringWidth(popup, fm,
                                                          title);

    textLoc.y = y + ascent + TEXT_SPACING;
    textLoc.x = x + ((width - stringWidth) / 2);

    g.setColor(background);
    g.fillRect(textLoc.x - TEXT_SPACING, textLoc.y - (fontHeight-descent),
               stringWidth + (2 * TEXT_SPACING), fontHeight - descent);
    g.setColor(foreground);
    SwingUtilities2.drawString(popup, g, title, textLoc.x, textLoc.y);

    MotifGraphicsUtils.drawGroove(g, x, textLoc.y + TEXT_SPACING,
                                  width, GROOVE_HEIGHT,
                                  shadowColor, highlightColor);

    g.setFont(origFont);
    g.setColor(origColor);
}
 
Example 20
Source File: SynthLabelUI.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public int getBaseline(JComponent c, int width, int height) {
    if (c == null) {
        throw new NullPointerException("Component must be non-null");
    }
    if (width < 0 || height < 0) {
        throw new IllegalArgumentException(
                "Width and height must be >= 0");
    }
    JLabel label = (JLabel)c;
    String text = label.getText();
    if (text == null || "".equals(text)) {
        return -1;
    }
    Insets i = label.getInsets();
    Rectangle viewRect = new Rectangle();
    Rectangle textRect = new Rectangle();
    Rectangle iconRect = new Rectangle();
    viewRect.x = i.left;
    viewRect.y = i.top;
    viewRect.width = width - (i.right + viewRect.x);
    viewRect.height = height - (i.bottom + viewRect.y);

    // layout the text and icon
    SynthContext context = getContext(label);
    FontMetrics fm = context.getComponent().getFontMetrics(
        context.getStyle().getFont(context));
    context.getStyle().getGraphicsUtils(context).layoutText(
        context, fm, label.getText(), label.getIcon(),
        label.getHorizontalAlignment(), label.getVerticalAlignment(),
        label.getHorizontalTextPosition(), label.getVerticalTextPosition(),
        viewRect, iconRect, textRect, label.getIconTextGap());
    View view = (View)label.getClientProperty(BasicHTML.propertyKey);
    int baseline;
    if (view != null) {
        baseline = BasicHTML.getHTMLBaseline(view, textRect.width,
                                             textRect.height);
        if (baseline >= 0) {
            baseline += textRect.y;
        }
    }
    else {
        baseline = textRect.y + fm.getAscent();
    }
    context.dispose();
    return baseline;
}