Java Code Examples for java.awt.FontMetrics

The following are top voted examples for showing how to use java.awt.FontMetrics. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: LivroJavaComoProgramar10Edicao   File: MetricsJPanel.java   View source code 7 votes vote down vote up
@Override
public void paintComponent(Graphics g)
{
   super.paintComponent(g); 

   g.setFont(new Font("SansSerif", Font.BOLD, 12));
   FontMetrics metrics = g.getFontMetrics();
   g.drawString("Current font: " + g.getFont(), 10, 30);
   g.drawString("Ascent: " + metrics.getAscent(), 10, 45);
   g.drawString("Descent: " + metrics.getDescent(), 10, 60);
   g.drawString("Height: " + metrics.getHeight(), 10, 75);
   g.drawString("Leading: " + metrics.getLeading(), 10, 90);

   Font font = new Font("Serif", Font.ITALIC, 14);
   metrics = g.getFontMetrics(font);
   g.setFont(font);
   g.drawString("Current font: " + font, 10, 120);
   g.drawString("Ascent: " + metrics.getAscent(), 10, 135);
   g.drawString("Descent: " + metrics.getDescent(), 10, 150);
   g.drawString("Height: " + metrics.getHeight(), 10, 165);
   g.drawString("Leading: " + metrics.getLeading(), 10, 180);
}
 
Example 2
Project: jdk8u-jdk   File: BasicLabelUI.java   View source code 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
Project: openjdk-jdk10   File: bug8132119.java   View source code 6 votes vote down vote up
private static void checkNullArgumentsGetStringWidth(JComponent comp,
        String text) {

    FontMetrics fontMetrics = comp.getFontMetrics(comp.getFont());
    BasicGraphicsUtils.getStringWidth(null, fontMetrics, text);
    float result = BasicGraphicsUtils.getStringWidth(comp, fontMetrics, null);

    if (result != 0) {
        throw new RuntimeException("The string length is not 0");
    }

    try {
        BasicGraphicsUtils.getStringWidth(comp, null, text);
    } catch (NullPointerException e) {
        return;
    }

    throw new RuntimeException("NPE is not thrown");
}
 
Example 4
Project: incubator-netbeans   File: ListCompletionView.java   View source code 6 votes vote down vote up
private void renderHtml(Fix f, Graphics g, Font defaultFont, Color defaultColor,
int width, int height, boolean selected) {
    if (icon != null) {
        // The image of the ImageIcon should already be loaded
        // so no ImageObserver should be necessary
        g.drawImage(ImageUtilities.icon2Image(icon), BEFORE_ICON_GAP, (height - icon.getIconHeight()) /2, this);
    }
    int iconWidth = BEFORE_ICON_GAP + icon.getIconWidth() + AFTER_ICON_GAP;
    int textEnd = width - AFTER_ICON_GAP - subMenuIcon.getIconWidth() - AFTER_TEXT_GAP;
    FontMetrics fm = g.getFontMetrics(defaultFont);
    int textY = (height - fm.getHeight())/2 + fm.getHeight() - fm.getDescent();

    // Render left text
    if (textEnd > iconWidth) { // any space for left text?
        HtmlRenderer.renderHTML(f.getText(), g, iconWidth, textY, textEnd, textY,
            defaultFont, defaultColor, HtmlRenderer.STYLE_TRUNCATE, true);//, selected);
    }

    if (HintsControllerImpl.getSubfixes(f).iterator().hasNext()) {
        paintArrowIcon(g, textEnd + AFTER_TEXT_GAP, (height - subMenuIcon.getIconHeight()) /2);
    }
}
 
Example 5
Project: jdk8u-jdk   File: KerningLeak.java   View source code 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 6
Project: sumo   File: BinaryDilation.java   View source code 6 votes vote down vote up
/**
 * Performs binary dilation.
 */
public void renderChar(FontMetrics fontMetrics, BufferedImage image, char c, int safetyMargin) {
	BufferedImage copy = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
	copy.getGraphics().drawImage(image, 0, 0, null);
	Graphics2D g = (Graphics2D) image.getGraphics();
	g.setColor(maskColor);
	
	for(int x=maskSize/2; x < image.getWidth()-maskSize/2; x++) {
		for(int y=maskSize/2; y < image.getHeight()-maskSize/2; y++) {
			
			if(PixelReplacer.INT_ARGBhasColor(copy.getRGB(x, y))) {
				for(int j=0;j<maskSize;j++) {
					for(int k=0;k<maskSize;k++) {
						g.drawLine(x+j-maskSize/2, y+k-maskSize/2, x+j-maskSize/2, y+k-maskSize/2);
					}
				}
			}
			
		}
	}
	
}
 
Example 7
Project: OpenJSharp   File: AquaTabbedPaneContrastUI.java   View source code 6 votes vote down vote up
protected void paintTitle(final Graphics2D g2d, final Font font, final FontMetrics metrics, final Rectangle textRect, final int tabIndex, final String title) {
    final View v = getTextViewForTab(tabIndex);
    if (v != null) {
        v.paint(g2d, textRect);
        return;
    }

    if (title == null) return;

    final Color color = tabPane.getForegroundAt(tabIndex);
    if (color instanceof UIResource) {
        g2d.setColor(getNonSelectedTabTitleColor());
        if (tabPane.getSelectedIndex() == tabIndex) {
            boolean pressed = isPressedAt(tabIndex);
            boolean enabled = tabPane.isEnabled() && tabPane.isEnabledAt(tabIndex);
            Color textColor = getSelectedTabTitleColor(enabled, pressed);
            Color shadowColor = getSelectedTabTitleShadowColor(enabled);
            AquaUtils.paintDropShadowText(g2d, tabPane, font, metrics, textRect.x, textRect.y, 0, 1, textColor, shadowColor, title);
            return;
        }
    } else {
        g2d.setColor(color);
    }
    g2d.setFont(font);
    SwingUtilities2.drawString(tabPane, g2d, title, textRect.x, textRect.y + metrics.getAscent());
}
 
Example 8
Project: scorekeeperfrontend   File: DriverTable.java   View source code 6 votes vote down vote up
@Override
public void paint(Graphics g1)
{
	Graphics2D g = (Graphics2D)g1;

	Dimension size = getSize();
	g.setColor(getBackground());
	g.fillRect(0, 0, size.width, size.height);
	g.setColor(new Color(40,40,40));

	//FontMetrics tm = g.getFontMetrics(topFont);
	FontMetrics bm = g.getFontMetrics(bottomFont);

	if (topLine != null)
	{
		g.setFont(topFont);
		g.drawString(topLine, 5, size.height/2 - 2);
	}
	if (bottomLine != null)
	{
		g.setFont(bottomFont);
		g.drawString(bottomLine, 5, size.height/2 + bm.getHeight() - 2);
	}
}
 
Example 9
Project: rekit-game   File: GameGridImpl.java   View source code 6 votes vote down vote up
/**
 * The implementation of
 * {@link #drawText(Vec, String, TextOptions, boolean)}.
 *
 * @param pos
 *            same as in base method
 * @param text
 *            same as in base method
 * @param options
 *            same as in base method
 */
private void drawTextImpl(Vec pos, String text, TextOptions options) {
	// Set color to red and set font
	RGBAColor in = options.getColor();
	RGBAColor col = (!options.getUseFilter() || this.filter == null || !this.filter.isApplyPixel()) ? in : this.filter.apply(in);
	this.graphics.setColor(this.calcRGBA(col));

	Font font = new Font(options.getFont(), options.getFontOptions(), options.getHeight());
	this.graphics.setFont(font);
	FontMetrics metrics = this.graphics.getFontMetrics(font);

	float x = pos.x;
	float y = pos.y;
	float xAlign = options.getAlignment().x;
	float yAlign = options.getAlignment().y;
	for (String line : text.split("\n")) {
		Dimension offset = this.getTextOffset(line, metrics);
		this.graphics.drawString(line, //
				(x + xAlign * offset.width), //
				(y += metrics.getHeight()) + yAlign * offset.height);
	}

}
 
Example 10
Project: parabuild-ci   File: MarkerAxisBand.java   View source code 6 votes vote down vote up
/**
 * A utility method that draws a string inside a rectangle.
 *
 * @param g2  the graphics device.
 * @param bounds  the rectangle.
 * @param font  the font.
 * @param text  the text.
 */
private void drawStringInRect(Graphics2D g2, Rectangle2D bounds, Font font,
                              String text) {

    g2.setFont(font);
    FontMetrics fm = g2.getFontMetrics(font);
    Rectangle2D r = TextUtilities.getTextBounds(text, g2, fm);
    double x = bounds.getX();
    if (r.getWidth() < bounds.getWidth()) {
        x = x + (bounds.getWidth() - r.getWidth()) / 2;
    }
    LineMetrics metrics = font.getLineMetrics(
        text, g2.getFontRenderContext()
    );
    g2.drawString(
        text, (float) x, (float) (bounds.getMaxY() 
            - this.bottomInnerGap - metrics.getDescent())
    );
}
 
Example 11
Project: incubator-netbeans   File: QueryTableCellRenderer.java   View source code 6 votes vote down vote up
private static String computeFitText(JLabel label) {
    String text = label.getText();
    if(text == null) text = "";
    if (text.length() <= VISIBLE_START_CHARS + 3) return text;
    
    Icon icon = label.getIcon();
    int iconWidth = icon != null ? icon.getIconWidth() : 0;
    
    FontMetrics fm = label.getFontMetrics(label.getFont());
    int width = label.getSize().width - iconWidth;

    String sufix = "...";                                                   // NOI18N
    int sufixLength = fm.stringWidth(sufix);
    int desired = width - sufixLength;
    if (desired <= 0) return text;

    for (int i = 0; i <= text.length() - 1; i++) {
        String prefix = text.substring(0, i);
        int swidth = fm.stringWidth(prefix);
        if (swidth >= desired) {
            return prefix.length() > 0 ? prefix + sufix: text;
        }
    }
    return text;
}
 
Example 12
Project: openjdk-jdk10   File: bug8132119.java   View source code 6 votes vote down vote up
private static void testStringWidth() {

        String str = "12345678910\u036F";
        JComponent comp = createComponent(str);
        Font font = comp.getFont();
        FontMetrics fontMetrics = comp.getFontMetrics(font);
        float stringWidth = BasicGraphicsUtils.getStringWidth(comp, fontMetrics, str);

        if (stringWidth == fontMetrics.stringWidth(str)) {
            throw new RuntimeException("Numeric shaper is not used!");
        }

        if (stringWidth != getLayoutWidth(str, font, NUMERIC_SHAPER)) {
            throw new RuntimeException("Wrong text width!");
        }
    }
 
Example 13
Project: incubator-netbeans   File: ColorEditor.java   View source code 6 votes vote down vote up
/** Paints the current value. Implements <code>ProepertyEditor</code> interface. */
public void paintValue(Graphics g, Rectangle rectangle) {
    int px;

    ((Graphics2D)g).setRenderingHints (getHints ());
    
    if (this.superColor != null) {
        Color color = g.getColor();
        g.drawRect(rectangle.x, rectangle.y + rectangle.height / 2 - 5 , 10, 10);
        g.setColor(this.superColor);
        g.fillRect(rectangle.x + 1, rectangle.y + rectangle.height / 2 - 4 , 9, 9);
        g.setColor(color);
        px = 18;
    }
    else px = 0;

    FontMetrics fm = g.getFontMetrics();
    g.drawString(getAsText(), rectangle.x + px, rectangle.y +
                  (rectangle.height - fm.getHeight()) / 2 + fm.getAscent());
}
 
Example 14
Project: incubator-netbeans   File: TaskListTable.java   View source code 6 votes vote down vote up
@Override
public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column ) {
        
    super.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column );

    int availableWidth = table.getColumnModel().getColumn( column ).getWidth();
    availableWidth -= table.getIntercellSpacing().getWidth();
    Insets borderInsets = getBorder().getBorderInsets( (Component)this );
    availableWidth -= (borderInsets.left + borderInsets.right);
    String cellText = getText();
    FontMetrics fm = getFontMetrics( getFont() );

    if( fm.stringWidth(cellText) > availableWidth ) {
        setToolTipText( cellText );

    } else {
        setToolTipText( null );
    }

    return this;
}
 
Example 15
Project: parabuild-ci   File: SubCategoryAxis.java   View source code 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 = 0.0;
        if (RectangleEdge.isLeftOrRight(edge)) {
            dim = bounds.getWidth();   
        }
        else {  // must be top or bottom
            dim = bounds.getHeight();
        }
        result = Math.max(result, dim);
    }   
    return result;
}
 
Example 16
Project: Tarski   File: mxUtils.java   View source code 5 votes vote down vote up
/**
 * Returns the font metrics of the static font graphics instance
 * 
 * @param font The font whose metrics are to be returned
 * @return the font metrics of the specified font
 */
public static FontMetrics getFontMetrics(Font font) {
  if (fontGraphics != null) {
    return fontGraphics.getFontMetrics(font);
  }

  return null;
}
 
Example 17
Project: jdk8u-jdk   File: Utilities.java   View source code 5 votes vote down vote up
static final int getTabbedTextOffset(View view, Segment s, FontMetrics metrics,
                                     int x0, int x, TabExpander e,
                                     int startOffset,
                                     int[] justificationData) {
    return getTabbedTextOffset(view, s, metrics, x0, x, e, startOffset, true,
                               justificationData);
}
 
Example 18
Project: parabuild-ci   File: ValueAxis.java   View source code 5 votes vote down vote up
/**
 * A utility method for determining the width of the widest tick label.
 *
 * @param ticks  the ticks.
 * @param g2  the graphics device.
 * @param drawArea  the area within which the plot and axes should be drawn.
 * @param vertical  a flag that indicates whether or not the tick labels 
 *                  are 'vertical'.
 *
 * @return The width of the tallest tick label.
 */
protected double findMaximumTickLabelWidth(List ticks, 
                                           Graphics2D g2, 
                                           Rectangle2D drawArea, 
                                           boolean vertical) {
                                               
    RectangleInsets insets = getTickLabelInsets();
    Font font = getTickLabelFont();
    double maxWidth = 0.0;
    if (!vertical) {
        FontMetrics fm = g2.getFontMetrics(font);
        Iterator iterator = ticks.iterator();
        while (iterator.hasNext()) {
            Tick tick = (Tick) iterator.next();
            Rectangle2D labelBounds = TextUtilities.getTextBounds(
                    tick.getText(), g2, fm);
            if (labelBounds.getWidth() + insets.getLeft() 
                    + insets.getRight() > maxWidth) {
                maxWidth = labelBounds.getWidth() 
                           + insets.getLeft() + insets.getRight();
            }
        }
    }
    else {
        LineMetrics metrics = font.getLineMetrics("ABCxyz", 
                g2.getFontRenderContext());
        maxWidth = metrics.getHeight() 
                   + insets.getTop() + insets.getBottom();
    }
    return maxWidth;
    
}
 
Example 19
Project: jmt   File: YAxisPlacer.java   View source code 5 votes vote down vote up
public void place(Graphics2D g, int xCoord) {
	int i;
	int newY;
	String l;
	DPoint p;
	FontMetrics fm;
	
	if (points == null || points.size()==0)
		return;

	p = points.get(0);
	l = labels.get(0);
	newY = 0;
	for (i = 0; i < labels.size(); i++) {
		l = labels.get(labels.size() - i - 1);
		p = points.get(points.size() - i - 1);
		fm = g.getFontMetrics();
		// if (p.getY() + fm.getStringBounds(l, g).getHeight()
		// + DistanceBetweenTwoLabels > previousY) {
		// overlapping
		// } else {
		//
		// }
		newY = (int) p.getY();
		g.drawString(l, xCoord, (int) (newY + fm.getStringBounds(l, g)
				.getHeight() / 4));
		// previousY = newY;
	}
}
 
Example 20
Project: parabuild-ci   File: ValueAxis.java   View source code 5 votes vote down vote up
/**
 * A utility method for determining the height of the tallest tick label.
 *
 * @param ticks  the ticks.
 * @param g2  the graphics device.
 * @param drawArea  the area within which the plot and axes should be drawn.
 * @param vertical  a flag that indicates whether or not the tick labels 
 *                  are 'vertical'.
 *
 * @return The height of the tallest tick label.
 */
protected double findMaximumTickLabelHeight(List ticks,
                                            Graphics2D g2, 
                                            Rectangle2D drawArea, 
                                            boolean vertical) {
                                                
    RectangleInsets insets = getTickLabelInsets();
    Font font = getTickLabelFont();
    double maxHeight = 0.0;
    if (vertical) {
        FontMetrics fm = g2.getFontMetrics(font);
        Iterator iterator = ticks.iterator();
        while (iterator.hasNext()) {
            Tick tick = (Tick) iterator.next();
            Rectangle2D labelBounds = TextUtilities.getTextBounds(
                    tick.getText(), g2, fm);
            if (labelBounds.getWidth() + insets.getTop() 
                    + insets.getBottom() > maxHeight) {
                maxHeight = labelBounds.getWidth() 
                            + insets.getTop() + insets.getBottom();
            }
        }
    }
    else {
        LineMetrics metrics = font.getLineMetrics("ABCxyz", 
                g2.getFontRenderContext());
        maxHeight = metrics.getHeight() 
                    + insets.getTop() + insets.getBottom();
    }
    return maxHeight;
    
}
 
Example 21
Project: rapidminer   File: TabbedPaneUI.java   View source code 5 votes vote down vote up
@Override
protected void paintText(Graphics g, int tabPlacement, Font font, FontMetrics metrics, int tabIndex, String title,
		Rectangle textRect, boolean isSelected) {
	// otherwise the tabs text would not have AA for some reason even though the rest of the
	// components has AA without this
	((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
	if (isSelected) {
		font = font.deriveFont(Font.BOLD);
	}
	super.paintText(g, tabPlacement, font, metrics, tabIndex, title, textRect, isSelected);
}
 
Example 22
Project: openjdk-jdk10   File: SunGraphics2D.java   View source code 5 votes vote down vote up
public FontMetrics getFontMetrics() {
    if (this.fontMetrics != null) {
        return this.fontMetrics;
    }
    /* NB the constructor and the setter disallow "font" being null */
    return this.fontMetrics =
       FontDesignMetrics.getMetrics(font, getFontRenderContext());
}
 
Example 23
Project: incubator-netbeans   File: CodeFoldingSideBar.java   View source code 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 24
Project: Logisim   File: TablePanel.java   View source code 5 votes vote down vote up
private void computePreferredSize() {
	Model model = getModel();
	Selection sel = model.getSelection();
	int columns = sel.size();
	if (columns == 0) {
		setPreferredSize(new Dimension(0, 0));
		return;
	}

	Graphics g = getGraphics();
	if (g == null) {
		cellHeight = 16;
		cellWidth = 24;
	} else {
		FontMetrics fm = g.getFontMetrics(HEAD_FONT);
		cellHeight = fm.getHeight();
		cellWidth = 24;
		for (int i = 0; i < columns; i++) {
			String header = sel.get(i).toShortString();
			Value value = model.getValueLog(sel.get(i)).get(0);
			String s = value == null ? "" : value.toDisplayString(sel.get(i).getRadix());
			cellWidth = Math.max(Math.max(cellWidth, fm.stringWidth(header)), fm.stringWidth(s));
		}
	}

	tableWidth = (cellWidth + COLUMN_SEP) * columns - COLUMN_SEP;
	tableHeight = cellHeight * (1 + rowCount) + HEADER_SEP;
	setPreferredSize(new Dimension(tableWidth, tableHeight));
	revalidate();
	repaint();
}
 
Example 25
Project: openjdk-jdk10   File: LWTextComponentPeer.java   View source code 5 votes vote down vote up
public Dimension getMinimumSize(final int rows, final int columns) {
    final Insets insets;
    synchronized (getDelegateLock()) {
        insets = getTextComponent().getInsets();
    }
    final int borderHeight = insets.top + insets.bottom;
    final int borderWidth = insets.left + insets.right;
    final FontMetrics fm = getFontMetrics(getFont());
    return new Dimension(fm.charWidth(WIDE_CHAR) * columns + borderWidth,
                         fm.getHeight() * rows + borderHeight);
}
 
Example 26
Project: incubator-netbeans   File: FontMetricsCache.java   View source code 5 votes vote down vote up
/** Get the font-metrics for the given font.
* @param font font for which the metrics is being retrieved.
* @param c component that is used to retrieve the metrics in case it's
*   not yet in the cache.
*/
public static synchronized FontMetrics getFontMetrics(Font f, Component c) {
    Object fm = font2FM.get(f);
    if (fm == null) {
        fm = c.getFontMetrics(f);
        font2FM.put(f, fm);
    }
    return (FontMetrics)fm;
}
 
Example 27
Project: incubator-netbeans   File: FontMetricsCache.java   View source code 5 votes vote down vote up
/** Get the font-metrics for the given font.
* @param font font for which the metrics is being retrieved.
* @param g graphics that is used to retrieve the metrics in case it's
*   not yet in the cache.
*/
public static synchronized FontMetrics getFontMetrics(Font f, Graphics g) {
    Object fm = font2FM.get(f);
    if (fm == null) {
        fm = g.getFontMetrics(f);
        font2FM.put(f, fm);
    }
    return (FontMetrics)fm;
}
 
Example 28
Project: openjdk-jdk10   File: Utilities.java   View source code 5 votes vote down vote up
static final int getBreakLocation(Segment s, FontMetrics metrics,
                                  float x0, float x, TabExpander e,
                                  int startOffset, boolean useFPIAPI) {
    char[] txt = s.array;
    int txtOffset = s.offset;
    int txtCount = s.count;
    int index = getTabbedTextOffset(null, s, metrics, x0, x, e, startOffset,
                                    false, null, useFPIAPI);

    if (index >= txtCount - 1) {
        return txtCount;
    }

    for (int i = txtOffset + index; i >= txtOffset; i--) {
        char ch = txt[i];
        if (ch < 256) {
            // break on whitespace
            if (Character.isWhitespace(ch)) {
                index = i - txtOffset + 1;
                break;
            }
        } else {
            // a multibyte char found; use BreakIterator to find line break
            BreakIterator bit = BreakIterator.getLineInstance();
            bit.setText(s);
            int breakPos = bit.preceding(i + 1);
            if (breakPos > txtOffset) {
                index = breakPos - txtOffset;
            }
            break;
        }
    }
    return index;
}
 
Example 29
Project: ramus   File: CloseableTabbedPane.java   View source code 5 votes vote down vote up
/**
 * Layouts the label
 *
 * @param tabPlacement the placement of the tabs
 * @param metrics      the font metrics
 * @param tabIndex     the index of the tab
 * @param title        the title of the tab
 * @param icon         the icon of the tab
 * @param tabRect      the tab boundaries
 * @param iconRect     the icon boundaries
 * @param textRect     the text boundaries
 * @param isSelected   true whether the tab is selected, false otherwise
 */
protected void layoutLabel(int tabPlacement, FontMetrics metrics,
                           int tabIndex, String title, Icon icon, Rectangle tabRect,
                           Rectangle iconRect, Rectangle textRect, boolean isSelected) {

    textRect.x = textRect.y = iconRect.x = iconRect.y = 0;

    javax.swing.text.View v = getTextViewForTab(tabIndex);
    if (v != null) {
        tabPane.putClientProperty("html", v);
    }

    SwingUtilities.layoutCompoundLabel(tabPane, metrics, title, icon,
            SwingUtilities.CENTER, SwingUtilities.CENTER,
            SwingUtilities.CENTER,
            // SwingUtilities.TRAILING,
            horizontalTextPosition, tabRect, iconRect, textRect,
            textIconGap + 2);

    tabPane.putClientProperty("html", null);

    int xNudge = getTabLabelShiftX(tabPlacement, tabIndex, isSelected);
    int yNudge = getTabLabelShiftY(tabPlacement, tabIndex, isSelected);
    iconRect.x += xNudge;
    iconRect.y += yNudge;
    textRect.x += xNudge;
    textRect.y += yNudge;
}
 
Example 30
Project: geomapapp   File: GeneralUtils.java   View source code 5 votes vote down vote up
/**
 * Place a string in the center of a bounding rectangle (eg a plot), with an optional white box 
 * behind the text
 * @param g
 * @param text
 * @param rect
 * @param font
 * @param xScale
 * @param yScale
 * @param whiteBox
 */
public static void drawCenteredString(Graphics g, String text, Rectangle2D rect, Font font, double xScale, 
		double yScale, boolean whiteBox) {
	// Get the original font
	Font oldFont = g.getFont();
    // Get the FontMetrics
    FontMetrics metrics = g.getFontMetrics(font);
    // Determine the X coordinate for the text
    int x = (int) ((rect.getWidth()* xScale  - metrics.stringWidth(text))  / 2);
    // Determine the Y coordinate for the text (note we add the ascent, as in java 2d 0 is top of the screen)
    int y = (int) ((rect.getHeight() * yScale - metrics.getHeight()) / 2) + metrics.getAscent();
    // Set the font
    Graphics2D g2 = (Graphics2D) g;
    g2.setFont(font);
    
    if (whiteBox) {
    	//draw a white box behind the text
	    int textWidth = (int) font.getStringBounds(text, g2.getFontRenderContext()).getWidth() + 2;
	    int textHeight = metrics.getHeight() + 2;
	    Color oldColor = g2.getColor();
	    g2.setColor(Color.white);
	    g2.fillRect(x-1, y-textHeight+4, textWidth, textHeight);
	    g2.setColor(oldColor);
    }
    
    // Draw the String
    g.drawString(text, x , y);
    // Reset font
    g.setFont(oldFont);
}
 
Example 31
Project: OpenJSharp   File: SunGraphics2D.java   View source code 5 votes vote down vote up
public FontMetrics getFontMetrics() {
    if (this.fontMetrics != null) {
        return this.fontMetrics;
    }
    /* NB the constructor and the setter disallow "font" being null */
    return this.fontMetrics =
       FontDesignMetrics.getMetrics(font, getFontRenderContext());
}
 
Example 32
Project: powertext   File: LineNumberList.java   View source code 5 votes vote down vote up
/**
 * Changes the width of the cells in the JList so you can see every digit
 * of each.
 */
void updateCellWidths() {

	int oldCellWidth = cellWidth;
	cellWidth = getRhsBorderWidth();

	// Adjust the amount of space the line numbers take up, if necessary.
	if (textArea!=null) {
		Font font = getFont();
		if (font!=null) {
			FontMetrics fontMetrics = getFontMetrics(font);
			int count = 0;
			int lineCount = textArea.getLineCount() +
					getLineNumberingStartIndex() - 1;
			do {
				lineCount = lineCount/10;
				count++;
			} while (lineCount >= 10);
			cellWidth += fontMetrics.charWidth('9')*(count+1) + 3;
		}
	}

	if (cellWidth!=oldCellWidth) { // Always true
		revalidate();
	}

}
 
Example 33
Project: jdk8u-jdk   File: SunGraphics2D.java   View source code 5 votes vote down vote up
public FontMetrics getFontMetrics(Font font) {
    if ((this.fontMetrics != null) && (font == this.font)) {
        return this.fontMetrics;
    }
    FontMetrics fm =
      FontDesignMetrics.getMetrics(font, getFontRenderContext());

    if (this.font == font) {
        this.fontMetrics = fm;
    }
    return fm;
}
 
Example 34
Project: Logisim   File: TextFieldCaret.java   View source code 5 votes vote down vote up
@Override
public Bounds getBounds(Graphics g) {
	int x = field.getX();
	int y = field.getY();
	Font font = field.getFont();
	FontMetrics fm;
	if (font == null)
		fm = g.getFontMetrics();
	else
		fm = g.getFontMetrics(font);
	int width = fm.stringWidth(curText);
	int ascent = fm.getAscent();
	int descent = fm.getDescent();
	int height = ascent + descent;
	switch (field.getHAlign()) {
	case TextField.H_CENTER:
		x -= width / 2;
		break;
	case TextField.H_RIGHT:
		x -= width;
		break;
	default:
		break;
	}
	switch (field.getVAlign()) {
	case TextField.V_TOP:
		y += ascent;
		break;
	case TextField.V_CENTER:
		y += (ascent - descent) / 2;
		break;
	case TextField.V_BOTTOM:
		y -= descent;
		break;
	default:
		break;
	}
	return Bounds.create(x, y - ascent, width, height).add(field.getBounds(g)).expand(3);
}
 
Example 35
Project: jmt   File: XAxisPlacer.java   View source code 5 votes vote down vote up
public void place(Graphics2D g, int yLabelCoord, int yMarkCoord) {
	int i;
	int previousX, newX, y;
	String l;
	DPoint p;
	FontMetrics fm;

	p = points.get(0);
	l = labels.get(0);
	previousX = 0;
	for (i = 0; i < labels.size(); i++) {
		l = labels.get(i);
		p = points.get(i);
		fm = g.getFontMetrics();
		newX = (int) (p.getX() - fm.getStringBounds(l, g).getWidth() / 2);
		if (newX < previousX + DISTANCE_BETWEEN_TWO_LABELS) {
			continue;
		}
		if (i % 2 == 0)
			y = yLabelCoord;
		else
			y = yLabelCoord + ODD_ADJUSTMENT;
		g.drawString(l, newX, y);
		g.draw(new Line2D.Double(p.getX(), yMarkCoord - MARK_WIDTH / 2, p
				.getX(), yMarkCoord + MARK_WIDTH / 2));
		previousX = (int) (newX + fm.getStringBounds(l, g).getWidth());
	}
}
 
Example 36
Project: Logisim   File: GraphicsUtil.java   View source code 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 37
Project: parabuild-ci   File: MeterLegend.java   View source code 5 votes vote down vote up
/**
 * Creates a legend item
 *
 * @param graphics  the graphics device.
 * @param item  the legend item.
 * @param x  the x coordinate.
 * @param y  the y coordinate.
 *
 * @return the legend item.
 */
private DrawableLegendItem createLegendItem(Graphics graphics,
                                            LegendItem item, double x, double y) {

    int innerGap = 2;
    FontMetrics fm = graphics.getFontMetrics();
    LineMetrics lm = fm.getLineMetrics(item.getLabel(), graphics);
    float textHeight = lm.getHeight();

    DrawableLegendItem drawable = new DrawableLegendItem(item);

    float xloc = (float) (x + innerGap + 1.15f * textHeight);
    float yloc = (float) (y + innerGap + (textHeight - lm.getLeading() - lm.getDescent()));

    drawable.setLabelPosition(new Point2D.Float(xloc, yloc));

    float boxDim = textHeight * 0.70f;
    xloc = (float) (x + innerGap + 0.15f * textHeight);
    yloc = (float) (y + innerGap + 0.15f * textHeight);

    drawable.setMarker(new Rectangle2D.Float(xloc, yloc, boxDim, boxDim));

    float width = (float) (drawable.getLabelPosition().getX() - x
                           + fm.stringWidth(item.getLabel()) + 0.5 * textHeight);

    float height = 2 * innerGap + textHeight;
    drawable.setBounds(x, y, width, height);
    return drawable;

}
 
Example 38
Project: rapidminer   File: TabbedPaneUI.java   View source code 5 votes vote down vote up
@Override
protected FontMetrics getFontMetrics() {
	Font font = tabPane.getFont();
	// selected tab is bold, to avoid resizing always assume bold and make tabs bigger
	font = font.deriveFont(Font.BOLD);
	return tabPane.getFontMetrics(font);
}
 
Example 39
Project: incubator-netbeans   File: AquaViewTabDisplayerUI.java   View source code 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 40
Project: OpenJSharp   File: DitherTest.java   View source code 5 votes vote down vote up
@Override
public void paint(Graphics g) {
    int w = getSize().width;
    int h = getSize().height;
    if (img == null) {
        super.paint(g);
        g.setColor(Color.black);
        FontMetrics fm = g.getFontMetrics();
        int x = (w - fm.stringWidth(calcString)) / 2;
        int y = h / 2;
        g.drawString(calcString, x, y);
    } else {
        g.drawImage(img, 0, 0, w, h, this);
    }
}