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: Tarski   File: mxUtils.java   Source Code and License 8 votes vote down vote up
/**
 * Returns an <mxRectangle> with the size (width and height in pixels) of the given string.
 * 
 * @param text String whose size should be returned.
 * @param font Font to be used for the computation.
 */
public static mxRectangle getSizeForString(String text, Font font, double scale) {
  FontRenderContext frc = new FontRenderContext(null, false, false);
  font = font.deriveFont((float) (font.getSize2D() * scale));
  FontMetrics metrics = null;

  if (fontGraphics != null) {
    metrics = fontGraphics.getFontMetrics(font);
  }

  double lineHeight = mxConstants.LINESPACING;

  if (metrics != null) {
    lineHeight += metrics.getHeight();
  } else {
    lineHeight += font.getSize2D() * 1.27;
  }

  String[] lines = text.split("\n");

  Rectangle2D boundingBox = null;

  if (lines.length == 0) {
    boundingBox = font.getStringBounds("", frc);
  } else {
    for (int i = 0; i < lines.length; i++) {
      Rectangle2D bounds = font.getStringBounds(lines[i], frc);

      if (boundingBox == null) {
        boundingBox = bounds;
      } else {
        boundingBox.setFrame(0, 0, Math.max(boundingBox.getWidth(), bounds.getWidth()),
            boundingBox.getHeight() + lineHeight);
      }
    }
  }

  return new mxRectangle(boundingBox);
}
 
Example 2
Project: LivroJavaComoProgramar10Edicao   File: MetricsJPanel.java   Source Code and License 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 3
Project: jdk8u-jdk   File: BasicLabelUI.java   Source Code and License 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 4
Project: openjdk-jdk10   File: bug8132119.java   Source Code and License 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 5
Project: incubator-netbeans   File: ListCompletionView.java   Source Code and License 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 6
Project: jdk8u-jdk   File: KerningLeak.java   Source Code and License 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 7
Project: sumo   File: BinaryDilation.java   Source Code and License 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 8
Project: OpenJSharp   File: AquaTabbedPaneContrastUI.java   Source Code and License 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 9
Project: scorekeeperfrontend   File: DriverTable.java   Source Code and License 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 10
Project: rekit-game   File: GameGridImpl.java   Source Code and License 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 11
Project: parabuild-ci   File: MarkerAxisBand.java   Source Code and License 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 12
Project: incubator-netbeans   File: QueryTableCellRenderer.java   Source Code and License 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 13
Project: openjdk-jdk10   File: bug8132119.java   Source Code and License 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 14
Project: incubator-netbeans   File: ColorEditor.java   Source Code and License 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 15
Project: incubator-netbeans   File: TaskListTable.java   Source Code and License 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 16
Project: Equella   File: FlatterTabbedPaneUI.java   Source Code and License 6 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)
{
	g.setFont(font);

	View v = getTextViewForTab(tabIndex);
	if( v != null )
	{
		// html
		v.paint(g, textRect);
	}
	else
	{
		// plain text
		int mnemIndex = tabPane.getDisplayedMnemonicIndexAt(tabIndex);

		if( tabPane.isEnabled() && tabPane.isEnabledAt(tabIndex) )
		{
			g.setColor(isSelected ? Color.white : Color.black);
			BasicGraphicsUtils.drawStringUnderlineCharAt(g, title, mnemIndex, textRect.x,
				textRect.y + metrics.getAscent());
		}
		else
		{ // tab disabled
			g.setColor(tabPane.getBackgroundAt(tabIndex).brighter());
			BasicGraphicsUtils.drawStringUnderlineCharAt(g, title, mnemIndex, textRect.x,
				textRect.y + metrics.getAscent());
			g.setColor(tabPane.getBackgroundAt(tabIndex).darker());
			BasicGraphicsUtils.drawStringUnderlineCharAt(g, title, mnemIndex, textRect.x,
				textRect.y + metrics.getAscent());
		}
	}
}
 
Example 17
Project: parabuild-ci   File: SubCategoryAxis.java   Source Code and License 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 18
Project: Tarski   File: mxUtils.java   Source Code and License 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 19
Project: jdk8u-jdk   File: Utilities.java   Source Code and License 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 20
Project: parabuild-ci   File: ValueAxis.java   Source Code and License 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 21
Project: jmt   File: YAxisPlacer.java   Source Code and License 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 22
Project: parabuild-ci   File: ValueAxis.java   Source Code and License 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 23
Project: rapidminer   File: TabbedPaneUI.java   Source Code and License 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 24
Project: openjdk-jdk10   File: SunGraphics2D.java   Source Code and License 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 25
Project: incubator-netbeans   File: CodeFoldingSideBar.java   Source Code and License 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 26
Project: Logisim   File: TablePanel.java   Source Code and License 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 27
Project: openjdk-jdk10   File: LWTextComponentPeer.java   Source Code and License 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 28
Project: incubator-netbeans   File: FontMetricsCache.java   Source Code and License 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 29
Project: incubator-netbeans   File: FontMetricsCache.java   Source Code and License 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 30
Project: openjdk-jdk10   File: Utilities.java   Source Code and License 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 31
Project: ramus   File: CloseableTabbedPane.java   Source Code and License 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 32
Project: geomapapp   File: GeneralUtils.java   Source Code and License 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 33
Project: powertext   File: LineNumberList.java   Source Code and License 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 34
Project: jdk8u-jdk   File: SunGraphics2D.java   Source Code and License 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 35
Project: Logisim   File: TextFieldCaret.java   Source Code and License 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 36
Project: jmt   File: XAxisPlacer.java   Source Code and License 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 37
Project: Logisim   File: GraphicsUtil.java   Source Code and License 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 38
Project: parabuild-ci   File: MeterLegend.java   Source Code and License 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 39
Project: rapidminer   File: TabbedPaneUI.java   Source Code and License 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 40
Project: incubator-netbeans   File: AquaViewTabDisplayerUI.java   Source Code and License 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 41
Project: OpenJSharp   File: DitherTest.java   Source Code and License 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);
    }
}
 
Example 42
Project: parabuild-ci   File: ValueAxis.java   Source Code and License 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) {
                                               
    Insets 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.left + insets.right > maxWidth) {
                maxWidth = labelBounds.getWidth() + insets.left + insets.right;
            }
        }
    }
    else {
        LineMetrics metrics = font.getLineMetrics("ABCxyz", g2.getFontRenderContext());
        maxWidth = metrics.getHeight() + insets.top + insets.bottom;
    }
    return maxWidth;
    
}
 
Example 43
Project: EMC   File: IFont.java   Source Code and License 5 votes vote down vote up
private BufferedImage getFontImage(final char ch, final boolean antiAlias) {
	final BufferedImage tempfontImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
	final Graphics2D g = (Graphics2D) tempfontImage.getGraphics();
	if (antiAlias)
		g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
	else
		g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
	g.setFont(font);
	final FontMetrics fontMetrics = g.getFontMetrics();
	int charwidth = fontMetrics.charWidth(ch) + 8;

	if (charwidth <= 0)
		charwidth = 7;
	int charheight = fontMetrics.getHeight() + 3;
	if (charheight <= 0)
		charheight = font.getSize();
	final BufferedImage fontImage = new BufferedImage(charwidth, charheight, BufferedImage.TYPE_INT_ARGB);
	final Graphics2D gt = (Graphics2D) fontImage.getGraphics();
	if (antiAlias)
		gt.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
	else
		gt.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
	gt.setFont(font);
	gt.setColor(Color.WHITE);
	final int charx = 3;
	final int chary = 1;
	gt.drawString(String.valueOf(ch), charx, chary + fontMetrics.getAscent());

	return fontImage;

}
 
Example 44
Project: incubator-netbeans   File: GtkEditorTabDisplayerUI.java   Source Code and License 5 votes vote down vote up
public Dimension getPreferredSize(JComponent c) {
    int prefHeight = 28;
    Graphics g = BasicScrollingTabDisplayerUI.getOffscreenGraphics();
    if (g != null) {
        FontMetrics fm = g.getFontMetrics(displayer.getFont());
        Insets ins = getTabAreaInsets();
        prefHeight = fm.getHeight() + ins.top + ins.bottom + 12;
    }
    return new Dimension(displayer.getWidth(), prefHeight);
}
 
Example 45
Project: openjdk-jdk10   File: ComponentOperator.java   Source Code and License 5 votes vote down vote up
/**
 * Maps {@code Component.getFontMetrics(Font)} through queue
 */
public FontMetrics getFontMetrics(final Font font) {
    return (runMapping(new MapAction<FontMetrics>("getFontMetrics") {
        @Override
        public FontMetrics map() {
            return getSource().getFontMetrics(font);
        }
    }));
}
 
Example 46
Project: VASSAL-src   File: Labeler.java   Source Code and License 5 votes vote down vote up
public BufferedImage eval() throws Exception {
  // determine whether we are HTML and fix our size
  final JLabel label = buildDimensions();

  // draw nothing if our size is zero
  if (size.width <= 0 || size.height <= 0) return ImageUtils.NULL_IMAGE;

  // prepare the target image
  final BufferedImage im = ImageUtils.createCompatibleImage(
    size.width,
    size.height,
    bg == null || bg.getTransparency() != Color.OPAQUE
  );

  final Graphics2D g = im.createGraphics();
  g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                     RenderingHints.VALUE_ANTIALIAS_ON);

  // paint the background
  if (bg != null) {
    g.setColor(bg);
    g.fillRect(0, 0, size.width, size.height);
  }

  // paint the foreground
  if (fg != null) {
    if (label != null) {
      label.paint(g);
    }
    else {
      g.setColor(fg);
      g.setFont(font);

      final FontMetrics fm = g.getFontMetrics(font);
      g.drawString(txt, 0, size.height - fm.getDescent());
    }
  }

  g.dispose();
  return im;
}
 
Example 47
Project: slick   File: Test_SlickLayout.java   Source Code and License 5 votes vote down vote up
public void paintComponent(Graphics g)
{
	super.paintComponent(g);
	
	FontMetrics fm = g.getFontMetrics();
	int strw = fm.stringWidth(name);
	int strh = fm.getHeight();
	g.drawString(name, (getSize().width-strw)/2, (getSize().height+strh)/2);
}
 
Example 48
Project: openjdk-jdk10   File: bug8132119.java   Source Code and License 5 votes vote down vote up
private static void testDrawString(boolean underlined) {
    String str = "AOB";
    JComponent comp = createComponent(str);

    BufferedImage buffImage = createBufferedImage(WIDTH, HEIGHT);
    Graphics2D g2 = buffImage.createGraphics();

    g2.setColor(DRAW_COLOR);
    g2.setFont(comp.getFont());

    FontMetrics fontMetrices = comp.getFontMetrics(comp.getFont());
    float width = BasicGraphicsUtils.getStringWidth(comp, fontMetrices, str);
    float x = (WIDTH - width) / 2;
    int y = 3 * HEIGHT / 4;

    if (underlined) {
        BasicGraphicsUtils.drawStringUnderlineCharAt(comp, g2, str, 1, x, y);
    } else {
        BasicGraphicsUtils.drawString(comp, g2, str, x, y);
    }
    g2.dispose();

    float xx = BasicGraphicsUtils.getStringWidth(comp, fontMetrices, "A") +
            BasicGraphicsUtils.getStringWidth(comp, fontMetrices, "O")/2;

    checkImageContainsSymbol(buffImage, (int) xx, underlined ? 3 : 2);
}
 
Example 49
Project: incubator-netbeans   File: ColorEditor.java   Source Code and License 5 votes vote down vote up
/** Overrides default preferredSize impl.
 * @return Standard method returned preferredSize
 * (depends on font size only).
 */
@Override
public Dimension getPreferredSize () {
    try {
        FontMetrics fontMetrics = this.getFontMetrics(this.getFont());
        return new Dimension (
                   fontMetrics.stringWidth (names [index]) + 30,
                   fontMetrics.getHeight () + 4
               );
    } catch (NullPointerException e) {
        return new Dimension (10, 10);
    }
}
 
Example 50
Project: Princeton_Algorithms   File: StdDraw.java   Source Code and License 5 votes vote down vote up
/**
 * Write the given text string in the current font, right-aligned at (<em>x</em>, <em>y</em>).
 *
 * @param  x the <em>x</em>-coordinate of the text
 * @param  y the <em>y</em>-coordinate of the text
 * @param  text the text to write
 */
public static void textRight(double x, double y, String text) {
    if (text == null) throw new IllegalArgumentException();
    offscreen.setFont(font);
    FontMetrics metrics = offscreen.getFontMetrics();
    double xs = scaleX(x);
    double ys = scaleY(y);
    int ws = metrics.stringWidth(text);
    int hs = metrics.getDescent();
    offscreen.drawString(text, (float) (xs - ws), (float) (ys + hs));
    draw();
}
 
Example 51
Project: parabuild-ci   File: DateAxis.java   Source Code and License 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.
 */
private double estimateMaximumTickLabelHeight(Graphics2D g2, 
                                              DateTickUnit unit) {

    RectangleInsets tickLabelInsets = getTickLabelInsets();
    double result = tickLabelInsets.getTop() + tickLabelInsets.getBottom();

    Font tickLabelFont = getTickLabelFont();
    FontRenderContext frc = g2.getFontRenderContext();
    LineMetrics lm = tickLabelFont.getLineMetrics("ABCxyz", frc);
    if (!isVerticalTickLabels()) {
        // all tick labels have the same width (equal to the height of 
        // the font)...
        result += lm.getHeight();
    }
    else {
        // look at lower and upper bounds...
        DateRange range = (DateRange) getRange();
        Date lower = range.getLowerDate();
        Date upper = range.getUpperDate();
        String lowerStr = null;
        String upperStr = null;
        DateFormat formatter = getDateFormatOverride();
        if (formatter != null) {
            lowerStr = formatter.format(lower);
            upperStr = formatter.format(upper);
        }
        else {
            lowerStr = unit.dateToString(lower);
            upperStr = unit.dateToString(upper);
        }
        FontMetrics fm = g2.getFontMetrics(tickLabelFont);
        double w1 = fm.stringWidth(lowerStr);
        double w2 = fm.stringWidth(upperStr);
        result += Math.max(w1, w2);
    }

    return result;

}
 
Example 52
Project: openjdk-jdk10   File: Blink.java   Source Code and License 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 53
Project: etomica   File: Plot.java   Source Code and License 5 votes vote down vote up
public void plotStringCenter(String s, double x, double y) {
    int ix = xPixel(x);
    int iy = yPixel(y);
    FontMetrics fm = osg.getFontMetrics();
    int sw = fm.stringWidth(s);
    ix -= sw / 2;
    osg.drawString(s, ix, iy);
}
 
Example 54
Project: rapidminer   File: TabbedPaneUI.java   Source Code and License 5 votes vote down vote up
@Override
protected int calculateTabWidth(int tabPlacement, int tabIndex, FontMetrics metrics) {
	if (isDockingFrameworkTab()) {
		return super.calculateTabWidth(tabPlacement, tabIndex, metrics) - 5;
	}

	return super.calculateTabWidth(tabPlacement, tabIndex, metrics) + 5;
}
 
Example 55
Project: Logisim   File: EditableLabel.java   Source Code and License 5 votes vote down vote up
private void computeDimensions(Graphics g, Font font, FontMetrics fm) {
	String s = text;
	FontRenderContext frc = ((Graphics2D) g).getFontRenderContext();
	width = fm.stringWidth(s);
	ascent = fm.getAscent();
	descent = fm.getDescent();
	int[] xs = new int[s.length()];
	int[] ys = new int[s.length()];
	for (int i = 0; i < xs.length; i++) {
		xs[i] = fm.stringWidth(s.substring(0, i + 1));
		TextLayout lay = new TextLayout(s.substring(i, i + 1), font, frc);
		Rectangle2D rect = lay.getBounds();
		int asc = (int) Math.ceil(-rect.getMinY());
		int desc = (int) Math.ceil(rect.getMaxY());
		if (asc < 0)
			asc = 0;
		if (asc > 0xFFFF)
			asc = 0xFFFF;
		if (desc < 0)
			desc = 0;
		if (desc > 0xFFFF)
			desc = 0xFFFF;
		ys[i] = (asc << 16) | desc;
	}
	charX = xs;
	charY = ys;
	dimsKnown = true;
}
 
Example 56
Project: freecol   File: ImageLibrary.java   Source Code and License 5 votes vote down vote up
/**
 * Create a "chip" with the given text and colors.
 *
 * @param g Graphics2D for getting the FontMetrics.
 * @param text The text to display.
 * @param border The border {@code Color}.
 * @param background The background {@code Color}.
 * @param amount How much to fill the chip with the fill color
 * @param fill The fill {@code Color}.
 * @param foreground The foreground {@code Color}.
 * @param filled Whether the chip is filled or not
 * @return A chip.
 */
private BufferedImage createChip(Graphics2D g, String text,
                                 Color border, Color background,
                                 double amount, Color fill,
                                 Color foreground,
                                 Boolean filled) {
    Font font = FontLibrary.createFont(FontLibrary.FontType.SIMPLE,
        FontLibrary.FontSize.TINY, Font.BOLD, scaleFactor);
    FontMetrics fm = g.getFontMetrics(font);
    int padding = (int)(6 * scaleFactor);
    BufferedImage bi = new BufferedImage(fm.stringWidth(text) + padding,
        fm.getMaxAscent() + fm.getMaxDescent() + padding,
        BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = bi.createGraphics();
    g2.setFont(font);
    int width = bi.getWidth();
    int height = bi.getHeight();
    g2.setColor(border);
    g2.fillRect(0, 0, width, height);
    g2.setColor(background);
    g2.fillRect(1, 1, width - 2, height - 2);
    if (filled.equals(false)) {
        if (amount > 0.0 && amount <= 1.0) {
            g2.setColor(fill);
            g2.fillRect(1, 1, width - 2, (int)((height - 2) * amount));
        }
    }
    g2.setColor(foreground);
    g2.drawString(text, padding/2, fm.getMaxAscent() + padding/2);
    g2.dispose();
    return bi;
}
 
Example 57
Project: jdk8u-jdk   File: LWTextComponentPeer.java   Source Code and License 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 58
Project: incubator-netbeans   File: LineNumbersActionsBar.java   Source Code and License 5 votes vote down vote up
private boolean checkLinesWidth(Graphics g) {
    FontMetrics fm = g.getFontMetrics(getLinesFont());
    Rectangle2D rect = fm.getStringBounds(Integer.toString(linesCount), g);
    linesWidth = (int) rect.getWidth() + LINES_BORDER_WIDTH * 2;
    if (linesWidth != oldLinesWidth) {
        oldLinesWidth = linesWidth;
        revalidate();
        repaint();
        return true;
    }
    return false;
}
 
Example 59
Project: incubator-netbeans   File: QuickSearchPopup.java   Source Code and License 5 votes vote down vote up
/** Computes width of string up to maxCharCount, with font of given JComponent
 * and with maximum percentage of owning Window that can be taken */
private static int computeWidth (JComponent comp, int maxCharCount, int percent) {
    FontMetrics fm = comp.getFontMetrics(comp.getFont());
    int charW = fm.charWidth('X');
    int result = charW * maxCharCount;
    // limit width to 50% of containing window
    Window w = SwingUtilities.windowForComponent(comp);
    if (w != null) {
        result = Math.min(result, w.getWidth() * percent / 100);
    }
    return result;
}
 
Example 60
Project: EspressoViews   File: ColumnsAutoSizer.java   Source Code and License 5 votes vote down vote up
public static void sizeColumnsToFit(JTable table, int columnMargin) {
    JTableHeader tableHeader = table.getTableHeader();
    if(tableHeader == null) {
        return;
    } 
    FontMetrics headerFontMetrics = tableHeader.getFontMetrics(tableHeader.getFont());
    int[] minWidths = new int[table.getColumnCount()];
    int[] maxWidths = new int[table.getColumnCount()];
 
    for(int columnIndex = 0; columnIndex < table.getColumnCount(); columnIndex++) {
        int headerWidth = headerFontMetrics.stringWidth(table.getColumnName(columnIndex));
        minWidths[columnIndex] = headerWidth + columnMargin;
        int maxWidth = getMaximalRequiredColumnWidth(table, columnIndex, headerWidth);
        maxWidths[columnIndex] = Math.max(maxWidth, minWidths[columnIndex]) + columnMargin;
    }
    adjustMaximumWidths(table, minWidths, maxWidths);
    for(int i = 0; i < minWidths.length; i++) {
        if(minWidths[i] > 0) {
            table.getColumnModel().getColumn(i).setMinWidth(minWidths[i]);
        }
        if(maxWidths[i] > 0) {
            table.getColumnModel().getColumn(i).setMaxWidth(maxWidths[i]);
            table.getColumnModel().getColumn(i).setWidth(maxWidths[i]);
            table.getColumnModel().getColumn(i).setMinWidth(maxWidths[i]);                
        }
    }
}