Java Code Examples for java.awt.FontMetrics

The following examples show how to use java.awt.FontMetrics. 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: netbeans   Source File: FlatEditorTabCellRenderer.java    License: 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 2
Source Project: jdk8u60   Source File: BasicLabelUI.java    License: 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 3
Source Project: netbeans   Source File: LinkButton.java    License: 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 4
Source Project: cosmic   Source File: ConsoleProxyThumbnailHandler.java    License: 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 5
Source Project: Bytecoder   Source File: SwingUtilities2.java    License: 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 6
Source Project: openjdk-8   Source File: Figure.java    License: 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 7
Source Project: openjdk-8-source   Source File: KerningLeak.java    License: 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 8
Source Project: openjdk-jdk9   Source File: KerningLeak.java    License: 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 9
Source Project: coming   Source File: Cardumen_007_t.java    License: 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 10
Source Project: i18n-editor   Source File: TranslationTree.java    License: 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 11
Source Project: jpexs-decompiler   Source File: SyntaxStyle.java    License: 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 12
Source Project: jdk8u60   Source File: MotifBorders.java    License: 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 13
Source Project: jdk1.8-source-analysis   Source File: MotifBorders.java    License: 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 14
Source Project: ECG-Viewer   Source File: SubCategoryAxis.java    License: 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 15
Source Project: runelite   Source File: XpGlobesOverlay.java    License: 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 16
Source Project: jdk8u60   Source File: KerningLeak.java    License: 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 Project: seaglass   Source File: SeaGlassTabbedPaneUI.java    License: 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 18
Source Project: jdk8u-dev-jdk   Source File: BasicLabelUI.java    License: 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 19
Source Project: SortingAlgorithmAnimations   Source File: SortPanel.java    License: 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 20
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 21
Source Project: plugins   Source File: WidgetOverlay.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void renderProgressWidget(Graphics2D graphics)
{
	String text;
	int percentage;

	Widget bar = client.getWidget(WidgetInfo.PEST_CONTROL_ACTIVITY_BAR).getChild(0);
	Rectangle2D bounds = bar.getBounds().getBounds2D();

	Widget prgs = client.getWidget(WidgetInfo.PEST_CONTROL_ACTIVITY_PROGRESS).getChild(0);

	// At 0% the inner widget changes and your progress will not increase anymore
	if ((int) (prgs.getBounds().getX()) - bounds.getX() != 2)
	{
		percentage = 0;
		text = "FAILED";
	}
	else
	{
		percentage = (int) ((prgs.getBounds().getWidth() / bounds.getWidth()) * 100);
		text = percentage + "%";
	}

	Color color = Color.GREEN;
	if (percentage < 25)
	{
		color = Color.RED;
	}

	FontMetrics fm = graphics.getFontMetrics();
	Rectangle2D textBounds = fm.getStringBounds(text, graphics);
	int x = (int) (bounds.getX() - textBounds.getWidth() - 4);
	int y = (int) (bounds.getY() + fm.getHeight() - 2);

	graphics.setColor(Color.BLACK);
	graphics.drawString(text, x + 1, y + 1);
	graphics.setColor(color);
	graphics.drawString(text, x, y);
}
 
Example 22
/**
 * Returns the baseline.
 *
 * @throws NullPointerException {@inheritDoc}
 * @throws IllegalArgumentException {@inheritDoc}
 * @see javax.swing.JComponent#getBaseline(int, int)
 * @since 1.6
 */
public int getBaseline(JComponent c, int width, int height) {
    super.getBaseline(c, width, height);
    JLabel label = (JLabel)c;
    String text = label.getText();
    if (text == null || "".equals(text) || label.getFont() == null) {
        return -1;
    }
    FontMetrics fm = label.getFontMetrics(label.getFont());
    layout(label, fm, width, height);
    return BasicHTML.getBaseline(label, paintTextR.y, fm.getAscent(),
                                 paintTextR.width, paintTextR.height);
}
 
Example 23
Source Project: plugins   Source File: VirtualLevelsOverlay.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public Dimension render(Graphics2D graphics)
{
	if (consumers.isEmpty())
	{
		return null;
	}

	final MainBufferProvider bufferProvider = (MainBufferProvider) client.getBufferProvider();
	final int imageHeight = ((BufferedImage) bufferProvider.getImage()).getHeight();
	final int y = imageHeight - plugin.getReportButton().getHeight() - 1;

	graphics.drawImage(plugin.getReportButton(), REPORT_BUTTON_X_OFFSET, y, null);

	graphics.setFont(FontManager.getRunescapeSmallFont());
	FontMetrics fontMetrics = graphics.getFontMetrics();

	String date = DATE_FORMAT.format(new Date());
	final int dateWidth = fontMetrics.stringWidth(date);
	final int dateHeight = fontMetrics.getHeight();

	final int textX = REPORT_BUTTON_X_OFFSET + plugin.getReportButton().getWidth() / 2 - dateWidth / 2;
	final int textY = y + plugin.getReportButton().getHeight() / 2 + dateHeight / 2;

	graphics.setColor(Color.BLACK);
	graphics.drawString(date, textX + 1, textY + 1);

	graphics.setColor(Color.WHITE);
	graphics.drawString(date, textX, textY);

	// Request the queued screenshots to be taken,
	// now that the timestamp is visible.
	Consumer<Image> consumer;
	while ((consumer = consumers.poll()) != null)
	{
		drawManager.requestNextFrameListener(consumer);
	}

	return null;
}
 
Example 24
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 25
Source Project: brModelo   Source File: baseDrawerItem.java    License: 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 26
Source Project: ccu-historian   Source File: NumberAxis.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Estimates the maximum width of the tick labels, assuming the specified
 * tick unit is used.
 * <P>
 * Rather than computing the string bounds of every tick on the axis, we
 * just look at two values: the lower bound and the upper bound for the
 * axis.  These two values will usually be representative.
 *
 * @param g2  the graphics device.
 * @param unit  the tick unit to use for calculation.
 *
 * @return The estimated maximum width of the tick labels.
 */
protected double estimateMaximumTickLabelWidth(Graphics2D g2,
                                               TickUnit unit) {

    RectangleInsets tickLabelInsets = getTickLabelInsets();
    double result = tickLabelInsets.getLeft() + tickLabelInsets.getRight();

    if (isVerticalTickLabels()) {
        // all tick labels have the same width (equal to the height of the
        // font)...
        FontRenderContext frc = g2.getFontRenderContext();
        LineMetrics lm = getTickLabelFont().getLineMetrics("0", frc);
        result += lm.getHeight();
    }
    else {
        // look at lower and upper bounds...
        FontMetrics fm = g2.getFontMetrics(getTickLabelFont());
        Range range = getRange();
        double lower = range.getLowerBound();
        double upper = range.getUpperBound();
        String lowerStr, upperStr;
        NumberFormat formatter = getNumberFormatOverride();
        if (formatter != null) {
            lowerStr = formatter.format(lower);
            upperStr = formatter.format(upper);
        }
        else {
            lowerStr = unit.valueToString(lower);
            upperStr = unit.valueToString(upper);
        }
        double w1 = fm.stringWidth(lowerStr);
        double w2 = fm.stringWidth(upperStr);
        result += Math.max(w1, w2);
    }

    return result;

}
 
Example 27
Source Project: jdk8u-dev-jdk   Source File: Blink.java    License: 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 28
Source Project: JAVA-MVC-Swing-Monopoly   Source File: PlayerInfo.java    License: 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);
}
 
Example 29
Source Project: Bytecoder   Source File: SwingUtilities2.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the left side bearing of the first character of string. The
 * left side bearing is calculated from the passed in FontMetrics.
 *
 * @param c JComponent that will display the string
 * @param fm FontMetrics used to measure the String width
 * @param firstChar Character to get the left side bearing for.
 */
public static int getLeftSideBearing(JComponent c, FontMetrics fm,
                                     char firstChar) {
    int charIndex = (int) firstChar;
    if (charIndex < MAX_CHAR_INDEX && charIndex >= MIN_CHAR_INDEX) {
        byte[] lsbs = null;

        FontRenderContext frc = getFontRenderContext(c, fm);
        Font font = fm.getFont();
        synchronized (SwingUtilities2.class) {
            LSBCacheEntry entry = null;
            if (searchKey == null) {
                searchKey = new LSBCacheEntry(frc, font);
            } else {
                searchKey.reset(frc, font);
            }
            // See if we already have an entry for this pair
            for (LSBCacheEntry cacheEntry : fontCache) {
                if (searchKey.equals(cacheEntry)) {
                    entry = cacheEntry;
                    break;
                }
            }
            if (entry == null) {
                // No entry for this pair, add it.
                entry = searchKey;
                fontCache[nextIndex] = searchKey;
                searchKey = null;
                nextIndex = (nextIndex + 1) % CACHE_SIZE;
            }
            return entry.getLeftSideBearing(firstChar);
        }
    }
    return 0;
}
 
Example 30
Source Project: TencentKona-8   Source File: Utilities.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static final int getTabbedTextOffset(Segment s,
                                            FontMetrics metrics,
                                            int x0, int x, TabExpander e,
                                            int startOffset,
                                            boolean round) {
    return getTabbedTextOffset(null, s, metrics, x0, x, e, startOffset, round, null);
}