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

The following examples show how to use java.awt.FontMetrics#getDescent() . 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: 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 2
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 3
Source File: RotatedFontMetricsTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String ... args) {
    Font font = new Font(Font.DIALOG, Font.PLAIN, FONT_SIZE);
    Graphics2D g2d = createGraphics();

    FontMetrics ref = null;
    RuntimeException failure = null;
    for (int a = 0; a < 360; a += 15) {
        Graphics2D g = (Graphics2D)g2d.create();
        g.rotate(Math.toRadians(a));
        FontMetrics m = g.getFontMetrics(font);
        g.dispose();

        boolean status = true;
        if (ref == null) {
            ref = m;
        } else {
            status = ref.getAscent() == m.getAscent() &&
                    ref.getDescent() == m.getDescent() &&
                    ref.getLeading() == m.getLeading() &&
                    ref.getMaxAdvance() == m.getMaxAdvance();
        }

        System.out.printf("Metrics a%d, d%d, l%d, m%d (%d) %s\n",
                m.getAscent(), m.getDescent(), m.getLeading(), m.getMaxAdvance(),
                (int)a, status ? "OK" : "FAIL");

        if (!status && failure == null) {
            failure = new RuntimeException("Font metrics differ for angle " + a);
        }
    }
    if (failure != null) {
        throw failure;
    }
    System.out.println("done");
}
 
Example 4
Source File: UnicodeFont.java    From opsu with GNU General Public License v3.0 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 5
Source File: MotifBorders.java    From openjdk-jdk8u 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 6
Source File: baseDrawerItem.java    From brModelo with GNU General Public License v3.0 5 votes vote down vote up
private void medidaV(Graphics2D g, int l, int t) {
    FontMetrics fm = g.getFontMetrics();
    String vl = dono.FormateUnidadeMedida(height);
    int traco = width;
    int xIni = l;// + (traco) / 2;
    int xFim = xIni + traco;
    int yIni = t;
    int yFim = t + height;
    int xLin = l + (width / 2);

    g.drawLine(xIni, yIni, xFim, yIni);
    g.drawLine(xIni, yFim, xFim, yFim);
    g.drawLine(xLin, yIni, xLin, yFim);

    int degrees = isInvertido() ? 90 : -90;
    int desse = isInvertido() ? 0 : fm.stringWidth(vl);
    //int centra = fm.getHeight() / 2 - fm.getDescent();
    int centra = fm.getHeight() - fm.getDescent();
    centra = isInvertido() ? -centra : centra;

    AffineTransform at = AffineTransform.getRotateInstance(Math.toRadians(degrees));
    Font f = new Font(g.getFont().getName(), Font.BOLD, g.getFont().getSize());
    Font f2 = g.getFont();
    g.setFont(f.deriveFont(at));
    yIni = yIni + (height - fm.stringWidth(vl)) / 2 + desse;
    g.drawString(vl, xLin + centra, yIni);
    g.setFont(f2);
}
 
Example 7
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 8
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 9
Source File: LizzieFrame.java    From lizzie with GNU General Public License v3.0 5 votes vote down vote up
private void drawPonderingState(Graphics2D g, String text, int x, int y, double size) {
  int fontSize = (int) (max(mainPanel.getWidth(), mainPanel.getHeight()) * size);
  Font font = new Font(Lizzie.config.fontName, Font.PLAIN, fontSize);
  FontMetrics fm = g.getFontMetrics(font);
  int stringWidth = fm.stringWidth(text);
  // Truncate too long text when display switching prompt
  if (Lizzie.leelaz != null && Lizzie.leelaz.isLoaded()) {
    int mainBoardX = boardRenderer.getLocation().x;
    if (mainPanel.getWidth() > mainPanel.getHeight()
        && (mainBoardX > x)
        && stringWidth > (mainBoardX - x)) {
      text = Utils.truncateStringByWidth(text, fm, mainBoardX - x);
      stringWidth = fm.stringWidth(text);
    }
  }
  // Do nothing when no text
  if (stringWidth <= 0) {
    return;
  }
  int stringHeight = fm.getAscent() - fm.getDescent();
  int width = max(stringWidth, 1);
  int height = max((int) (stringHeight * 1.2), 1);

  BufferedImage result = new BufferedImage(width, height, TYPE_INT_ARGB);
  // commenting this out for now... always causing an exception on startup. will fix in the
  // upcoming refactoring
  //        filter20.filter(cachedBackground.getSubimage(x, y, result.getWidth(),
  // result.getHeight()), result);
  g.drawImage(result, x, y, null);

  g.setColor(new Color(0, 0, 0, 130));
  g.fillRect(x, y, width, height);
  g.drawRect(x, y, width, height);

  g.setColor(Color.white);
  g.setFont(font);
  g.drawString(
      text, x + (width - stringWidth) / 2, y + stringHeight + (height - stringHeight) / 2);
}
 
Example 10
Source File: StdDraw.java    From algs4 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Writes the given text string in the current font, left-aligned at (<em>x</em>, <em>y</em>).
 * @param  x the <em>x</em>-coordinate of the text
 * @param  y the <em>y</em>-coordinate of the text
 * @param  text the text
 * @throws IllegalArgumentException if {@code text} is {@code null}
 * @throws IllegalArgumentException if {@code x} or {@code y} is either NaN or infinite
 */
public static void textLeft(double x, double y, String text) {
    validate(x, "x");
    validate(y, "y");
    validateNotNull(text, "text");

    offscreen.setFont(font);
    FontMetrics metrics = offscreen.getFontMetrics();
    double xs = scaleX(x);
    double ys = scaleY(y);
    int hs = metrics.getDescent();
    offscreen.drawString(text, (float) xs, (float) (ys + hs));
    draw();
}
 
Example 11
Source File: GraphicsUtil.java    From Logisim with GNU General Public License v3.0 5 votes vote down vote up
static public Rectangle getTextBounds(Graphics g, String text, int x, int y, int halign, int valign) {
	if (g == null)
		return new Rectangle(x, y, 0, 0);
	FontMetrics mets = g.getFontMetrics();
	int width = mets.stringWidth(text);
	int ascent = mets.getAscent();
	int descent = mets.getDescent();
	int height = ascent + descent;

	Rectangle ret = new Rectangle(x, y, width, height);
	switch (halign) {
	case H_CENTER:
		ret.translate(-(width / 2), 0);
		break;
	case H_RIGHT:
		ret.translate(-width, 0);
		break;
	default:
		;
	}
	switch (valign) {
	case V_TOP:
		break;
	case V_CENTER:
		ret.translate(0, -(ascent / 2));
		break;
	case V_CENTER_OVERALL:
		ret.translate(0, -(height / 2));
		break;
	case V_BASELINE:
		ret.translate(0, -ascent);
		break;
	case V_BOTTOM:
		ret.translate(0, -height);
		break;
	default:
		;
	}
	return ret;
}
 
Example 12
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 13
Source File: AbstractWinViewTabDisplayerUI.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 ?
            17 : fm.getAscent() + 2 * fm.getDescent() + 3;
    Insets insets = c.getInsets();
    prefSize.height = height + insets.bottom + insets.top;
    return prefSize;
}
 
Example 14
Source File: baseDrawer.java    From brModelo with GNU General Public License v3.0 4 votes vote down vote up
public void bordaLeftRigth(Graphics2D g, boolean isrigth) {
        FontMetrics fm = g.getFontMetrics();
        String vl = FormateUnidadeMedida(H);
        int pre_x = (isrigth ? getLeftWidth() : getLeft());
        int traco = largTraco < margem ? largTraco : margem;
        traco = (isrigth ? -traco : traco);
        int xIni = pre_x + (isrigth ? -2 : 2);
        int xFim = xIni + 2 * traco;
        int yIni = getTop() + margem;
        int yFim = getTopHeight() - margem;
        int xLin = xIni;
//        int pre_x = (isrigth ? getLeftWidth() - margem : getLeft());
//        int traco = largTraco < margem ? largTraco : margem;
//        int xIni = pre_x + (margem - traco) / 2;
//        int xFim = xIni + traco;
//        int yIni = getTop() + margem;
//        int yFim = getTopHeight() - margem;
//        int xLin = pre_x + margem / 2;

        g.setColor(getCorRegua());
        g.drawLine(xIni, yIni, xFim, yIni);
        g.drawLine(xIni, yFim, xFim, yFim);
        g.drawLine(xLin, yIni, xLin, yFim);

        int blc = calculeSubEspaco(W);
        int sr = yIni;
        xFim -= traco;

        int dv = modInteiro(blc);
        int subblc = 0;
        if (dv > 0) {
            subblc = blc / dv;
        }
        while (sr < yFim) {
            if (dv > 0) {
                int a = blc - subblc;
                while (a > 0) {
                    if (sr + a < yFim) {
                        g.drawLine(xIni, sr + a, xFim - traco / 2, sr + a);
                    }
                    a -= subblc;
                }
            }
            g.drawLine(xIni, sr, xFim, sr);
            sr += blc;
        }

        if (isMostrarTextoRegua()) {
            int degrees = isrigth ? 90 : -90;
            int desse = isrigth ? 0 : fm.stringWidth(vl);
            int centra = fm.getHeight() / 2 - fm.getDescent();
            centra = isrigth ? -centra : centra;

            AffineTransform at = AffineTransform.getRotateInstance(Math.toRadians(degrees));
            Font f = new Font(getFont().getName(), Font.BOLD, getFont().getSize());
            g.setFont(f.deriveFont(at));
            g.setColor(getForeColor());
            xLin = pre_x - (isrigth ? margem / 2 : -margem / 2);
            yIni = yIni + (H - fm.stringWidth(vl)) / 2 + desse;
            g.drawString(vl, xLin + centra, yIni);
            g.setFont(getFont());
        }
    }
 
Example 15
Source File: MotifGraphicsUtils.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
static void drawStringInRect(JComponent c, Graphics g, String aString,
                                 int x, int y, int width, int height,
                                 int justification) {
        FontMetrics  fontMetrics;
        int          drawWidth, startX, startY, delta;

        if (g.getFont() == null) {
//            throw new InconsistencyException("No font set");
            return;
        }
        fontMetrics = SwingUtilities2.getFontMetrics(c, g);
        if (fontMetrics == null) {
//            throw new InconsistencyException("No metrics for Font " + font());
            return;
        }

        if (justification == CENTER) {
            drawWidth = SwingUtilities2.stringWidth(c, fontMetrics, aString);
            if (drawWidth > width) {
                drawWidth = width;
            }
            startX = x + (width - drawWidth) / 2;
        } else if (justification == RIGHT) {
            drawWidth = SwingUtilities2.stringWidth(c, fontMetrics, aString);
            if (drawWidth > width) {
                drawWidth = width;
            }
            startX = x + width - drawWidth;
        } else {
            startX = x;
        }

        delta = (height - fontMetrics.getAscent() - fontMetrics.getDescent()) / 2;
        if (delta < 0) {
            delta = 0;
        }

        startY = y + height - delta - fontMetrics.getDescent();

        SwingUtilities2.drawString(c, g, aString, startX, startY);
    }
 
Example 16
Source File: JLinkButton.java    From yeti with MIT License 4 votes vote down vote up
protected void paintText(Graphics g, JComponent com, Rectangle rect,
            String s) {
        JLinkButton bn = (JLinkButton) com;
        ButtonModel bnModel = bn.getModel();
//    Color color = bn.getForeground();
//    Object obj = null;
        if (bnModel.isEnabled()) {
            if (bnModel.isPressed()) {
                bn.setForeground(bn.getActiveLinkColor());
            } else if (bn.isLinkVisited()) {
                bn.setForeground(bn.getVisitedLinkColor());
            } else {
                bn.setForeground(bn.getLinkColor());
            }
        } else {
            if (bn.getDisabledLinkColor() != null) {
                bn.setForeground(bn.getDisabledLinkColor());
            }
        }
        super.paintText(g, com, rect, s);
        int behaviour = bn.getLinkBehavior();
        boolean drawLine = false;
        if (behaviour == JLinkButton.HOVER_UNDERLINE) {
            if (bnModel.isRollover()) {
                drawLine = true;
            }
        } else if (behaviour == JLinkButton.ALWAYS_UNDERLINE || behaviour == JLinkButton.SYSTEM_DEFAULT) {
            drawLine = true;
        }
        if (!drawLine) {
            return;
        }
        FontMetrics fm = g.getFontMetrics();
        int x = rect.x + getTextShiftOffset();
        int y = (rect.y + fm.getAscent() + fm.getDescent() + getTextShiftOffset()) - 1;
        if (bnModel.isEnabled()) {
            g.setColor(bn.getForeground());
            g.drawLine(x, y, (x + rect.width) - 1, y);
        } else {
            g.setColor(bn.getBackground().brighter());
            g.drawLine(x, y, (x + rect.width) - 1, y);
        }
    }
 
Example 17
Source File: MotifBorders.java    From JDKSourceCode1.8 with MIT License 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 18
Source File: BrowserDisplayer.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
     * Determine the alignment offset so the text is aligned with other views
     * correctly.
     */
    private float getPreferredAlignmentY() {
        // Fix for the Issue #68316
        Font font = getFont();
        FontMetrics fm = getToolkit().getFontMetrics(font);
        float h = fm.getHeight();
        float d = fm.getDescent();
        return (h - d) / h;

// Original implementation below is commented out due to Issue #68316.
// It tries also take into account a size of the icon, but according to javadoc
// of the class "Only text is supported".
// Original implementation is commented out below due to the bug #68316.
// It tries also to take into account a size of the icon, but according to
// javadoc of the class "Only text is supported".
//
//        Icon icon = (Icon)getIcon();
//        String text = getText();
//
//        Font font = getFont();
//        FontMetrics fm = getToolkit().getFontMetrics(font);
//
//        Rectangle iconR = new Rectangle();
//        Rectangle textR = new Rectangle();
//        Rectangle viewR = new Rectangle(Short.MAX_VALUE, Short.MAX_VALUE);
//
//        SwingUtilities.layoutCompoundLabel(
//            this, fm, text, icon,
//            getVerticalAlignment(), getHorizontalAlignment(),
//            getVerticalTextPosition(), getHorizontalTextPosition(),
//            viewR, iconR, textR,
//	    (text == null ? 0 : ((BasicButtonUI)ui).getDefaultTextIconGap(this))
//        );
//
//        // The preferred size of the button is the size of
//        // the text and icon rectangles plus the buttons insets.
//        Rectangle r = iconR.union(textR);
//
//        Insets insets = getInsets();
//        r.height += insets.top + insets.bottom;
//
//        // Ensure that the height of the button is odd,
//        // to allow for the focus line.
//        if(r.height % 2 == 0) {
//            r.height += 1;
//        }
//
//        float offAmt = fm.getMaxAscent() + insets.top;
//        return offAmt/(float)r.height;
    }
 
Example 19
Source File: ButtonUiStone.java    From settlers-remake with MIT License 4 votes vote down vote up
@Override
public void paint(Graphics g1, JComponent c) {
	Graphics2D g = DrawHelper.enableAntialiasing(g1);

	AbstractButton b = (AbstractButton) c;
	ButtonModel model = b.getModel();

	boolean down;
	if (c instanceof JToggleButton) {
		down = ((JToggleButton) c).isSelected();
	} else {
		down = model.isArmed() && model.isPressed();
	}

	BufferedImage bg;
	BufferedImage[] border;
	float scale = this.scale;

	if (down) {
		border = BORDER_DOWN;
		scale /= 2;
		bg = backgroundImagePressed;
	} else {
		bg = backgroundImage;
		border = BORDER_NORMAL;
	}

	// Draw background
	g.drawImage(bg, 0, 0, c);

	BorderHelper.drawBorder(g1, c, border, scale);

	FontMetrics fm = g.getFontMetrics();
	int y = (b.getHeight() - fm.getAscent() - fm.getDescent()) / 2 + fm.getAscent();
	int x = textPaddingLeftRight;

	if (down) {
		x += 1;
		y += 1;
	}

	g.setFont(c.getFont());

	// draw shadow
	g.setColor(Color.BLACK);
	g.drawString(b.getText(), x + 1, y + 1);
	g.setColor(c.getForeground());
	g.drawString(b.getText(), x, y);
}
 
Example 20
Source File: MotifGraphicsUtils.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
static void drawStringInRect(JComponent c, Graphics g, String aString,
                                 int x, int y, int width, int height,
                                 int justification) {
        FontMetrics  fontMetrics;
        int          drawWidth, startX, startY, delta;

        if (g.getFont() == null) {
//            throw new InconsistencyException("No font set");
            return;
        }
        fontMetrics = SwingUtilities2.getFontMetrics(c, g);
        if (fontMetrics == null) {
//            throw new InconsistencyException("No metrics for Font " + font());
            return;
        }

        if (justification == CENTER) {
            drawWidth = SwingUtilities2.stringWidth(c, fontMetrics, aString);
            if (drawWidth > width) {
                drawWidth = width;
            }
            startX = x + (width - drawWidth) / 2;
        } else if (justification == RIGHT) {
            drawWidth = SwingUtilities2.stringWidth(c, fontMetrics, aString);
            if (drawWidth > width) {
                drawWidth = width;
            }
            startX = x + width - drawWidth;
        } else {
            startX = x;
        }

        delta = (height - fontMetrics.getAscent() - fontMetrics.getDescent()) / 2;
        if (delta < 0) {
            delta = 0;
        }

        startY = y + height - delta - fontMetrics.getDescent();

        SwingUtilities2.drawString(c, g, aString, startX, startY);
    }