java.awt.FontMetrics Java Examples

The following examples show how to use java.awt.FontMetrics. 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 jdk1.8-source-analysis 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 #2
Source File: SubCategoryAxis.java    From ECG-Viewer with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the maximum of the relevant dimension (height or width) of the
 * subcategory labels.
 *
 * @param g2  the graphics device.
 * @param edge  the edge.
 *
 * @return The maximum dimension.
 */
private double getMaxDim(Graphics2D g2, RectangleEdge edge) {
    double result = 0.0;
    g2.setFont(this.subLabelFont);
    FontMetrics fm = g2.getFontMetrics();
    Iterator iterator = this.subCategories.iterator();
    while (iterator.hasNext()) {
        Comparable subcategory = (Comparable) iterator.next();
        String label = subcategory.toString();
        Rectangle2D bounds = TextUtilities.getTextBounds(label, g2, fm);
        double dim;
        if (RectangleEdge.isLeftOrRight(edge)) {
            dim = bounds.getWidth();
        }
        else {  // must be top or bottom
            dim = bounds.getHeight();
        }
        result = Math.max(result, dim);
    }
    return result;
}
 
Example #3
Source File: FlatEditorTabCellRenderer.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected int getCaptionYAdjustment() {
    // Workaround for a issue in AbstractTabCellRenderer.paintIconAndText(Graphics),
    // which uses font height (which includes font descent) to calculate Y-coordinate
    // when available height is equal to font height (availH <= txtH),
    // but HtmlRenderer.renderString() expects Y-coordinate at baseline.
    // So the text is painted vertically out of center.
    //
    // This seems to be no issue with other LAFs because they seem to use
    // TabPainter insets differently and the available height is larger than
    // the font height (availH > txtH), in which case 3 pixels are removed from
    // the Y-coordinate to avoid that the text is painted vertically out of center.

    FontMetrics fm = getFontMetrics(getFont());
    int txtH = fm.getHeight();
    Insets ins = getInsets();
    int availH = getHeight() - (ins.top + ins.bottom);
    return (availH <= txtH) ? -fm.getDescent() : -1;
}
 
Example #4
Source File: MotifBorders.java    From jdk8u60 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 #5
Source File: SortPanel.java    From SortingAlgorithmAnimations with MIT License 6 votes vote down vote up
@Override
protected void paintComponent(Graphics g) {
	super.paintComponent(g);
	
	//draw border
	g.setColor(Color.WHITE);
	g.drawRect(BORDER_WIDTH, BORDER_WIDTH, getWidth() - 2 * BORDER_WIDTH, getHeight() - 2 * BORDER_WIDTH);
	
	//draw title
	Font nameFont = new Font(Font.MONOSPACED, Font.BOLD, 18);
	FontMetrics nameFontMetrix = getFontMetrics(nameFont);		
	g.setColor(Color.BLACK);
	g.fillRect((getWidth() - nameFontMetrix.stringWidth(name)) / 2, 0, nameFontMetrix.stringWidth(name), BORDER_WIDTH + nameFontMetrix.getAscent() / 3);
	g.setColor(Color.WHITE);
	g.setFont(nameFont);
	g.drawString(name, (getWidth() - nameFontMetrix.stringWidth(name)) / 2, BORDER_WIDTH + nameFontMetrix.getAscent() / 3);

}
 
Example #6
Source File: SyntaxStyle.java    From jpexs-decompiler with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Draw text.  This can directly call the Utilities.drawTabbedText.
 * Sub-classes can override this method to provide any other decorations.
 * @param  segment - the source of the text
 * @param  x - the X origin >= 0
 * @param  y - the Y origin >= 0
 * @param  graphics - the graphics context
 * @param e - how to expand the tabs. If this value is null, tabs will be 
 * expanded as a space character.
 * @param startOffset - starting offset of the text in the document >= 0 
 * @return
 */   
 public int drawText(Segment segment, int x, int y,
        Graphics graphics, TabExpander e, int startOffset) {
    graphics.setFont(graphics.getFont().deriveFont(getFontStyle()));
    FontMetrics fontMetrics = graphics.getFontMetrics();
    int a = fontMetrics.getAscent();
    int h = a + fontMetrics.getDescent();
    //JPEXS: UniTools for multi fonts
    int w = UniTools.getTabbedTextWidth(graphics,segment,0, e, startOffset);
    int rX = x - 1;
    int rY = y - a;
    int rW = w + 2;
    int rH = h;
    if ((getFontStyle() & 0x10) != 0) {
        graphics.setColor(Color.decode("#EEEEEE"));
        graphics.fillRect(rX, rY, rW, rH);
    }
    graphics.setColor(getColor());
    //JPEXS: UniTools for multi fonts
    x = UniTools.drawTabbedText(segment, x, y, graphics, e, startOffset);
    if ((getFontStyle() & 0x8) != 0) {
        graphics.setColor(Color.RED);
        graphics.drawRect(rX, rY, rW, rH);
    }
    return x;
}
 
Example #7
Source File: TranslationTree.java    From i18n-editor with MIT License 6 votes vote down vote up
@Override
protected void paintComponent(Graphics g) {
	TranslationTreeCellRenderer renderer = (TranslationTreeCellRenderer) getCellRenderer();
	Color c1 = renderer.getSelectionBackground();
	
	FontMetrics metrics = g.getFontMetrics(getFont());
	setRowHeight(metrics.getHeight() + 8);
	
	g.setColor(getBackground());
       g.fillRect(0, 0, getWidth(), getHeight());
       
       for (int i : getSelectionRows()) {
       	Rectangle r = getRowBounds(i);
       	g.setColor(c1);
           g.fillRect(0, r.y, getWidth(), r.height);
       }
       
       super.paintComponent(g);
   }
 
Example #8
Source File: Cardumen_007_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Returns a rectangle that encloses the axis label.  This is typically 
 * used for layout purposes (it gives the maximum dimensions of the label).
 *
 * @param g2  the graphics device.
 * @param edge  the edge of the plot area along which the axis is measuring.
 *
 * @return The enclosing rectangle.
 */
protected Rectangle2D getLabelEnclosure(Graphics2D g2, RectangleEdge edge) {

    Rectangle2D result = new Rectangle2D.Double();
    String axisLabel = getLabel();
    if (axisLabel != null && !axisLabel.equals("")) {
        FontMetrics fm = g2.getFontMetrics(getLabelFont());
        Rectangle2D bounds = TextUtilities.getTextBounds(axisLabel, g2, fm);
        RectangleInsets insets = getLabelInsets();
        bounds = insets.createOutsetRectangle(bounds);
        double angle = getLabelAngle();
        if (edge == RectangleEdge.LEFT || edge == RectangleEdge.RIGHT) {
            angle = angle - Math.PI / 2.0;
        }
        double x = bounds.getCenterX();
        double y = bounds.getCenterY();
        AffineTransform transformer 
            = AffineTransform.getRotateInstance(angle, x, y);
        Shape labelBounds = transformer.createTransformedShape(bounds);
        result = labelBounds.getBounds2D();
    }

    return result;

}
 
Example #9
Source File: BasicLabelUI.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private String layout(JLabel label, FontMetrics fm,
                      int width, int height) {
    Insets insets = label.getInsets(null);
    String text = label.getText();
    Icon icon = (label.isEnabled()) ? label.getIcon() :
                                      label.getDisabledIcon();
    Rectangle paintViewR = new Rectangle();
    paintViewR.x = insets.left;
    paintViewR.y = insets.top;
    paintViewR.width = width - (insets.left + insets.right);
    paintViewR.height = height - (insets.top + insets.bottom);
    paintIconR.x = paintIconR.y = paintIconR.width = paintIconR.height = 0;
    paintTextR.x = paintTextR.y = paintTextR.width = paintTextR.height = 0;
    return layoutCL(label, fm, text, icon, paintViewR, paintIconR,
                    paintTextR);
}
 
Example #10
Source File: XpGlobesOverlay.java    From runelite with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void drawProgressLabel(Graphics2D graphics, XpGlobe globe, int startXp, int goalXp, int x, int y)
{
	if (goalXp <= globe.getCurrentXp())
	{
		return;
	}

	// Convert to int just to limit the decimal cases
	String progress = (int) (getSkillProgress(startXp, globe.getCurrentXp(), goalXp)) + "%";

	final FontMetrics metrics = graphics.getFontMetrics();
	int drawX = x + (config.xpOrbSize() / 2) - (metrics.stringWidth(progress) / 2);
	int drawY = y + (config.xpOrbSize() / 2) + (metrics.getHeight() / 2);

	OverlayUtil.renderTextLocation(graphics, new Point(drawX, drawY), progress, Color.WHITE);
}
 
Example #11
Source File: LinkButton.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void paint(Graphics g) {
    super.paint(g);
    if( underline && isEnabled() ) {
        Font f = getFont();
        FontMetrics fm = getFontMetrics(f);
        int iconWidth = 0;
        if( null != getIcon() ) {
            iconWidth = getIcon().getIconWidth()+getIconTextGap();
        }
        int x1 = iconWidth;
        int y1 = fm.getHeight();
        int x2 = fm.stringWidth(getText()) + iconWidth;
        if( getText().length() > 0 )
            g.drawLine(x1, y1, x2, y1);
    }
}
 
Example #12
Source File: KerningLeak.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void leak() {
    Map<TextAttribute, Object> textAttributes = new HashMap<>();
    textAttributes.put(TextAttribute.FAMILY, "Sans Serif");
    textAttributes.put(TextAttribute.SIZE, 12);
    textAttributes.put(TextAttribute.KERNING, TextAttribute.KERNING_ON);
    Font font = Font.getFont(textAttributes);
    JLabel label = new JLabel();
    int dummy = 0;
    for (int i = 0; i < 500; i++) {
        if (i % 10 == 0) System.out.println("Starting iter " + (i+1));
        for (int j = 0; j <1000; j++) {
            FontMetrics fm = label.getFontMetrics(font);
            dummy += SwingUtilities.computeStringWidth(fm, Integer.toString(j));
        }
    }
    System.out.println("done " + dummy);
}
 
Example #13
Source File: BasicLabelUI.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
private String layout(JLabel label, FontMetrics fm,
                      int width, int height) {
    Insets insets = label.getInsets(null);
    String text = label.getText();
    Icon icon = (label.isEnabled()) ? label.getIcon() :
                                      label.getDisabledIcon();
    Rectangle paintViewR = new Rectangle();
    paintViewR.x = insets.left;
    paintViewR.y = insets.top;
    paintViewR.width = width - (insets.left + insets.right);
    paintViewR.height = height - (insets.top + insets.bottom);
    paintIconR.x = paintIconR.y = paintIconR.width = paintIconR.height = 0;
    paintTextR.x = paintTextR.y = paintTextR.width = paintTextR.height = 0;
    return layoutCL(label, fm, text, icon, paintViewR, paintIconR,
                    paintTextR);
}
 
Example #14
Source File: KerningLeak.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private static void leak() {
    Map<TextAttribute, Object> textAttributes = new HashMap<>();
    textAttributes.put(TextAttribute.FAMILY, "Sans Serif");
    textAttributes.put(TextAttribute.SIZE, 12);
    textAttributes.put(TextAttribute.KERNING, TextAttribute.KERNING_ON);
    Font font = Font.getFont(textAttributes);
    JLabel label = new JLabel();
    int dummy = 0;
    for (int i = 0; i < 500; i++) {
        if (i % 10 == 0) System.out.println("Starting iter " + (i+1));
        for (int j = 0; j <1000; j++) {
            FontMetrics fm = label.getFontMetrics(font);
            dummy += SwingUtilities.computeStringWidth(fm, Integer.toString(j));
        }
    }
    System.out.println("done " + dummy);
}
 
Example #15
Source File: SeaGlassTabbedPaneUI.java    From seaglass with Apache License 2.0 6 votes vote down vote up
/**
 * @see javax.swing.plaf.basic.BasicTabbedPaneUI#getBaseline(int)
 */
protected int getBaseline(int tab) {
    if (tabPane.getTabComponentAt(tab) != null || getTextViewForTab(tab) != null) {
        return super.getBaseline(tab);
    }

    String      title   = tabPane.getTitleAt(tab);
    Font        font    = tabContext.getStyle().getFont(tabContext);
    FontMetrics metrics = getFontMetrics(font);
    Icon        icon    = getIconForTab(tab);

    textRect.setBounds(0, 0, 0, 0);
    iconRect.setBounds(0, 0, 0, 0);
    calcRect.setBounds(0, 0, Short.MAX_VALUE, maxTabHeight);
    tabContext.getStyle().getGraphicsUtils(tabContext).layoutText(tabContext, metrics, title, icon, SwingUtilities.CENTER,
                                                                  SwingUtilities.CENTER, SwingUtilities.LEADING,
                                                                  SwingUtilities.TRAILING, calcRect, iconRect, textRect, textIconGap);

    return textRect.y + metrics.getAscent() + getBaselineOffset();
}
 
Example #16
Source File: KerningLeak.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private static void leak() {
    Map<TextAttribute, Object> textAttributes = new HashMap<>();
    textAttributes.put(TextAttribute.FAMILY, "Sans Serif");
    textAttributes.put(TextAttribute.SIZE, 12);
    textAttributes.put(TextAttribute.KERNING, TextAttribute.KERNING_ON);
    Font font = Font.getFont(textAttributes);
    JLabel label = new JLabel();
    int dummy = 0;
    for (int i = 0; i < 500; i++) {
        if (i % 10 == 0) System.out.println("Starting iter " + (i+1));
        for (int j = 0; j <1000; j++) {
            FontMetrics fm = label.getFontMetrics(font);
            dummy += SwingUtilities.computeStringWidth(fm, Integer.toString(j));
        }
    }
    System.out.println("done " + dummy);
}
 
Example #17
Source File: ConsoleProxyThumbnailHandler.java    From cosmic with Apache License 2.0 6 votes vote down vote up
public static BufferedImage generateTextImage(final int w, final int h, final String text) {
    final BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR);
    final Graphics2D g = img.createGraphics();
    g.setColor(Color.BLACK);
    g.fillRect(0, 0, w, h);
    g.setColor(Color.WHITE);
    g.setFont(new Font(null, Font.PLAIN, 12));
    final FontMetrics fm = g.getFontMetrics();
    final int textWidth = fm.stringWidth(text);
    int startx = (w - textWidth) / 2;
    if (startx < 0) {
        startx = 0;
    }
    g.drawString(text, startx, h / 2);
    return img;
}
 
Example #18
Source File: Figure.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public int getWidth() {
    if (widthCash == -1) {
        int max = 0;
        BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        g.setFont(diagram.getFont());
        FontMetrics metrics = g.getFontMetrics();
        for (String s : lines) {
            int cur = metrics.stringWidth(s);
            if (cur > max) {
                max = cur;
            }
        }
        widthCash = max + INSET;
    }
    return widthCash;
}
 
Example #19
Source File: SwingUtilities2.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
public static float getFontCharsWidth(char[] data, int offset, int len,
                                      FontMetrics fm,
                                      boolean useFPAPI)
{
    if (len == 0) {
       return 0;
    }
    if (useFPAPI) {
        Rectangle2D bounds = fm.getFont().
                                 getStringBounds(data, offset, offset + len,
                                                 fm.getFontRenderContext());
        return (float) bounds.getWidth();
    } else {
        return fm.charsWidth(data, offset, len);
    }
}
 
Example #20
Source File: CyclicNumberAxis.java    From ECG-Viewer with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Reserve some space on each axis side because we draw a centered label at
 * each extremity.
 *
 * @param g2  the graphics device.
 * @param plot  the plot.
 * @param plotArea  the plot area.
 * @param edge  the edge.
 * @param space  the space already reserved.
 *
 * @return The reserved space.
 */
@Override
public AxisSpace reserveSpace(Graphics2D g2, Plot plot,
        Rectangle2D plotArea, RectangleEdge edge, AxisSpace space) {

    this.internalMarkerCycleBoundTick = null;
    AxisSpace ret = super.reserveSpace(g2, plot, plotArea, edge, space);
    if (this.internalMarkerCycleBoundTick == null) {
        return ret;
    }

    FontMetrics fm = g2.getFontMetrics(getTickLabelFont());
    Rectangle2D r = TextUtilities.getTextBounds(
        this.internalMarkerCycleBoundTick.getText(), g2, fm
    );

    if (RectangleEdge.isTopOrBottom(edge)) {
        if (isVerticalTickLabels()) {
            space.add(r.getHeight() / 2, RectangleEdge.RIGHT);
        }
        else {
            space.add(r.getWidth() / 2, RectangleEdge.RIGHT);
        }
    }
    else if (RectangleEdge.isLeftOrRight(edge)) {
        if (isVerticalTickLabels()) {
            space.add(r.getWidth() / 2, RectangleEdge.TOP);
        }
        else {
            space.add(r.getHeight() / 2, RectangleEdge.TOP);
        }
    }

    return ret;

}
 
Example #21
Source File: RotatedFontMetricsTest.java    From TencentKona-8 with GNU General Public License v2.0 5 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 #22
Source File: TextUtils.java    From orson-charts with GNU General Public License v3.0 5 votes vote down vote up
/**
 * A utility method that calculates the anchor offsets for a string.
 * Normally, the {@code (x, y)} coordinate for drawing text is a point on 
 * the baseline at the left of the text string.  If you add these offsets 
 * to {@code (x, y)} and draw the string, then the anchor point should 
 * coincide with the {@code (x, y)} point.
 *
 * @param g2  the graphics device (not {@code null}).
 * @param text  the text.
 * @param anchor  the anchor point ({@code null} not permitted).
 *
 * @return  The offsets.
 */
private static float[] deriveTextBoundsAnchorOffsets(Graphics2D g2,
        String text, TextAnchor anchor) {

    float[] result = new float[2];
    FontRenderContext frc = g2.getFontRenderContext();
    Font f = g2.getFont();
    FontMetrics fm = g2.getFontMetrics(f);
    Rectangle2D bounds = getTextBounds(text, fm);
    LineMetrics metrics = f.getLineMetrics(text, frc);
    float ascent = metrics.getAscent();
    float halfAscent = ascent / 2.0f;
    float descent = metrics.getDescent();
    float leading = metrics.getLeading();
    float xAdj = 0.0f;
    float yAdj = 0.0f;

    if (anchor.isHorizontalCenter()) {
        xAdj = (float) -bounds.getWidth() / 2.0f;
    } else if (anchor.isRight()) {
        xAdj = (float) -bounds.getWidth();
    }

    if (anchor.isTop()) {
        yAdj = -descent - leading + (float) bounds.getHeight();
    } else if (anchor.isHalfAscent()) {
        yAdj = halfAscent;
    } else if (anchor.isHalfHeight()) {
        yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0);
    } else if (anchor.isBaseline()) {
        yAdj = 0.0f;
    } else if (anchor.isBottom()) {
        yAdj = -metrics.getDescent() - metrics.getLeading();
    }
    result[0] = xAdj;
    result[1] = yAdj;
    return result;
}
 
Example #23
Source File: MultiAxisLineGraph2DRenderer.java    From diirt with MIT License 5 votes vote down vote up
private static void drawVerticalReferenceLabelSplit(Graphics2D graphics, FontMetrics metrics, String text, int xCenter, int[] drawRange, int yTop, boolean updateMin, boolean centeredOnly) {
    // If the center is not in the range, don't draw anything
    if (drawRange[MAX] < xCenter || drawRange[MIN] > xCenter)
        return;

    // If there is no space, don't draw anything
    if (drawRange[MAX] - drawRange[MIN] < metrics.getHeight())
        return;

    Java2DStringUtilities.Alignment alignment = Java2DStringUtilities.Alignment.TOP;
    int targetX = xCenter;
    int halfWidth = metrics.stringWidth(text) / 2;
    if (xCenter < drawRange[MIN] + halfWidth) {
        // Can't be drawn in the center
        if (centeredOnly)
            return;
        alignment = Java2DStringUtilities.Alignment.TOP_LEFT;
        targetX = drawRange[MIN];
    } else if (xCenter > drawRange[MAX] - halfWidth) {
        // Can't be drawn in the center
        if (centeredOnly)
            return;
        alignment = Java2DStringUtilities.Alignment.TOP_RIGHT;
        targetX = drawRange[MAX];
    }

    Java2DStringUtilities.drawString(graphics, alignment, targetX, yTop, text);

    if (updateMin) {
        drawRange[MIN] = targetX + metrics.getHeight();
    } else {
        drawRange[MAX] = targetX - metrics.getHeight();
    }
}
 
Example #24
Source File: BasicLabelUI.java    From jdk1.8-source-analysis with Apache License 2.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 #25
Source File: Blink.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void paint(Graphics g) {
    int fontSize = g.getFont().getSize();
    int x = 0, y = fontSize, space;
    int red = (int) (50 * Math.random());
    int green = (int) (50 * Math.random());
    int blue = (int) (256 * Math.random());
    Dimension d = getSize();
    g.setColor(Color.black);
    FontMetrics fm = g.getFontMetrics();
    space = fm.stringWidth(" ");
    for (StringTokenizer t = new StringTokenizer(labelString);
            t.hasMoreTokens();) {
        String word = t.nextToken();
        int w = fm.stringWidth(word) + space;
        if (x + w > d.width) {
            x = 0;
            y += fontSize;  //move word to next line if it doesn't fit
        }
        if (Math.random() < 0.5) {
            g.setColor(new java.awt.Color((red + y * 30) % 256,
                    (green + x / 3) % 256, blue));
        } else {
            g.setColor(getBackground());
        }
        g.drawString(word, x, y);
        x += w;  //shift to the right to draw the next word
    }
}
 
Example #26
Source File: LGraphics.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
public void drawCenterRoundedString(String s, int x, int y, Color color, Color color1) {
	g2d.setColor(color);
	FontMetrics fontmetrics = g2d.getFontMetrics();
	x -= fontmetrics.stringWidth(s) >> 1;
	y += fontmetrics.getAscent() - fontmetrics.getDescent() >> 1;
	g2d.drawString(s, x + 1, y + 1);
	g2d.drawString(s, x + 1, y - 1);
	g2d.drawString(s, x - 1, y + 1);
	g2d.drawString(s, x - 1, y - 1);
	g2d.setColor(color1);
	g2d.drawString(s, x, y);
}
 
Example #27
Source File: MotifPopupMenuUI.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public Dimension getPreferredSize(JComponent c) {
    LayoutManager layout = c.getLayout();
    Dimension d = layout.preferredLayoutSize(c);
    String title = ((JPopupMenu)c).getLabel();
    if (titleFont == null) {
        UIDefaults table = UIManager.getLookAndFeelDefaults();
        titleFont = table.getFont("PopupMenu.font");
    }
    FontMetrics fm = c.getFontMetrics(titleFont);
    int         stringWidth = 0;

    if (title!=null) {
        stringWidth += SwingUtilities2.stringWidth(c, fm, title);
    }

    if (d.width < stringWidth) {
        d.width = stringWidth + 8;
        Insets i = c.getInsets();
        if (i!=null) {
            d.width += i.left + i.right;
        }
        if (border != null) {
            i = border.getBorderInsets(c);
            d.width += i.left + i.right;
        }

        return d;
    }
    return null;
}
 
Example #28
Source File: MultiLineToolTip.java    From pdfxtk with Apache License 2.0 5 votes vote down vote up
public void paint(Graphics g, JComponent c) {
     FontMetrics metrics = g.getFontMetrics();
     Dimension size = c.getSize();
     g.setColor(c.getBackground());
     g.fillRect(0, 0, size.width, size.height);
     g.setColor(c.getForeground());
     int y = metrics.getAscent() + 1;
     int h = metrics.getHeight();
     if(lines != null)
for (int i = 0; i < lines.length; i++) {
  g.drawString(lines[i], 3, y);
  y += h;
}
   }
 
Example #29
Source File: TextBoxPanel.java    From energy2d with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static JComboBox<Integer> createFontSizeComboBox() {
	JComboBox<Integer> c = new JComboBox<Integer>(FONT_SIZE);
	c.setToolTipText("Font size");
	FontMetrics fm = c.getFontMetrics(c.getFont());
	int w = fm.stringWidth(FONT_SIZE[FONT_SIZE.length - 1].toString()) + 40;
	int h = fm.getHeight() + 8;
	c.setPreferredSize(new Dimension(w, h));
	c.setEditable(false);
	c.setRequestFocusEnabled(false);
	return c;
}
 
Example #30
Source File: PlayerInfo.java    From JAVA-MVC-Swing-Monopoly with Apache License 2.0 5 votes vote down vote up
private void drawPlayers(Graphics g) {
	int y = 92;
	for (PlayerModel a : players) {
		drawPlayer(g,a,y);
		y += 180;
	}
	String str = "";
	if (GameRunning.day >= GameRunning.GAME_DAY) {
		str ="�ﵽ��Ϸ���� "+GameRunning.GAME_DAY+" ��.";
	}
	//����Ǯ
	PlayerModel p1 = players.get(0);
	PlayerModel p2 = players.get(1);
	if (GameRunning.MONEY_MAX > 0 && p1.getCash() >= GameRunning.MONEY_MAX) {
		str ="\"" + p1.getName() +"\" ��Ǯ�ﵽ��Ϸ��Ǯ����.";
	} else if (GameRunning.MONEY_MAX > 0 && p2.getCash() >= GameRunning.MONEY_MAX) {
		str ="\"" + p2.getName() +"\" ��Ǯ�ﵽ��Ϸ��Ǯ����.";
	}
	// �Ʋ�
	if (p1.getCash() < 0 ){
		str ="\"" + p1.getName() +"\"�Ʋ�.";
	} else if (p2.getCash() < 0 ){
		str ="\"" + p2.getName() +"\"�Ʋ�.";
	}
	FontMetrics fm = g.getFontMetrics();
	g.drawString("����ԭ��"+str, 200 - fm.stringWidth(str)/2, 86);
}