Java Code Examples for java.awt.Graphics.getFontMetrics()

The following are Jave code examples for showing how to use getFontMetrics() of the java.awt.Graphics class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: java_mooc_fi   File: HangmanFigure.java   View Source Code Vote up 6 votes
public void drawString(Graphics g, String string, int x, int y, int width) {
    FontMetrics fontMetrics = g.getFontMetrics();
    int lineHeight = fontMetrics.getHeight();

    int curX = x;
    int curY = y;

    String[] words = string.split(" ");

    for (String word : words) {
        // Find out thw width of the word.
        int wordWidth = fontMetrics.stringWidth(word + " ");

        // If text exceeds the width, then move to next line.
        if (curX + wordWidth >= x + width) {
            curY += lineHeight;
            curX = x;
        }

        g.drawString(word, curX, curY);

        // Move over to the right for next word.
        curX += wordWidth;
    }
}
 
Example 2
Project: Logisim   File: TableTab.java   View Source Code Vote up 6 votes
private void computePreferredSize() {
	int inputs = table.getInputColumnCount();
	int outputs = table.getOutputColumnCount();
	if (inputs == 0 && outputs == 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;
		if (inputs == 0 || outputs == 0) {
			cellWidth = Math.max(cellWidth, fm.stringWidth(Strings.get("tableNullHeader")));
		}
		for (int i = 0; i < inputs + outputs; i++) {
			String header = i < inputs ? table.getInputHeader(i) : table.getOutputHeader(i - inputs);
			cellWidth = Math.max(cellWidth, fm.stringWidth(header));
		}
	}

	if (inputs == 0)
		inputs = 1;
	if (outputs == 0)
		outputs = 1;
	tableWidth = (cellWidth + COLUMN_SEP) * (inputs + outputs) - COLUMN_SEP;
	tableHeight = cellHeight * (1 + table.getRowCount()) + HEADER_SEP;
	setPreferredSize(new Dimension(tableWidth, tableHeight));
	revalidate();
	repaint();
}
 
Example 3
Project: openjdk-jdk10   File: Slot.java   View Source Code Vote up 6 votes
public int getWidth() {
    if (shortName == null || shortName.length() <= 1) {
        return Figure.SLOT_WIDTH;
    } else {
        BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        g.setFont(figure.getDiagram().getSlotFont().deriveFont(Font.BOLD));
        FontMetrics metrics = g.getFontMetrics();
        return Math.max(Figure.SLOT_WIDTH, metrics.stringWidth(shortName) + 6);
    }
}
 
Example 4
Project: Logisim   File: ExpressionView.java   View Source Code Vote up 5 votes
public void setExpression(Expression expr) {
	ExpressionData exprData = new ExpressionData(expr);
	Graphics g = getGraphics();
	FontMetrics fm = g == null ? null : g.getFontMetrics();
	renderData = new RenderData(exprData, getWidth(), fm);
	setPreferredSize(renderData.getPreferredSize());
	revalidate();
	repaint();
}
 
Example 5
Project: incubator-netbeans   File: HeapView.java   View Source Code Vote up 5 votes
/**
 * Renders the text.
 */
private void paintText(Graphics g, int w, int h) {
    g.setFont(getFont());
    String text = getHeapSizeText();
    FontMetrics fm = g.getFontMetrics();
    int textWidth = fm.stringWidth(text);
    g.drawString(text, (w - maxTextWidth) / 2 + (maxTextWidth - textWidth), 
            h / 2 + fm.getAscent() / 2 - 2);
}
 
Example 6
Project: WordnetLoom   File: NodeDrawer.java   View Source Code Vote up 5 votes
/**
 * probne rysowanie - policznie wymiarow w dół
 *
 * @param g - kontekst graficzny
 */
public void trialDrawY(Graphics g) {
    if (itemsToDraw == null) {
        return;
    }

    // policzenie wymiarow
    FontMetrics metrics = g.getFontMetrics();
    fontHeight = metrics.getHeight();
    int pos = fontHeight;
    int length = 0;
    for (String text : itemsToDraw) {
        length = Math.max(length, metrics.stringWidth(text));
        pos += fontHeight;
    }
    dimension.width = length + 4;
    dimension.height = pos - fontHeight + 4;

    // policzenie obrysu z dziecmi
    bound.width = 0;
    bound.height = 0;
    for (NodeDrawer node : nodes) {
        node.trialDrawY(g);
        bound.width += node.getBound().width + X_DISTANCE;
        bound.height = Math.max(node.getBound().height, bound.height);
    }
    bound.width = Math.max(dimension.width, bound.width - X_DISTANCE);
    bound.height = dimension.height + Y_DISTANCE + bound.height;

    // korekta na odstep
    if (nodes.isEmpty()) {
        bound.height -= Y_DISTANCE;
    }
}
 
Example 7
Project: oxygen-git-plugin   File: ToolbarPanel.java   View Source Code Vote up 5 votes
/**
* Create "Pull" button.
* 
* @return the "Pull" button.
*/
private ToolbarButton createPullButton() {
  return new ToolbarButton(createPullAction(), false) {
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);

		String str = "";
		if (pullsBehind > 0) {
			str = "" + pullsBehind;
		}
		if (pullsBehind > 9) {
			pullButton.setHorizontalAlignment(SwingConstants.LEFT);
		} else {
			pullButton.setHorizontalAlignment(SwingConstants.CENTER);
		}
		g.setFont(g.getFont().deriveFont(Font.BOLD, 8.5f));
		FontMetrics fontMetrics = g.getFontMetrics(g.getFont());
		int stringWidth = fontMetrics.stringWidth(str);
		int stringHeight = fontMetrics.getHeight();
		g.setColor(new Color(255, 255, 255, 100));
		g.fillRect(pullButton.getWidth() - stringWidth, 0, stringWidth, stringHeight);
		g.setColor(Color.BLACK);
		g.drawString(str, pullButton.getWidth() - stringWidth,
				fontMetrics.getHeight() - fontMetrics.getDescent() - fontMetrics.getLeading());
	}
};
}
 
Example 8
Project: incubator-netbeans   File: WinClassicEditorTabDisplayerUI.java   View Source Code Vote up 5 votes
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 + (isGenericUI ? 5 : 6);
    }
    return new Dimension(displayer.getWidth(), prefHeight);
}
 
Example 9
Project: incubator-netbeans   File: FontMetricsCache.java   View Source Code Vote up 5 votes
/** 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 10
Project: Logisim   File: GraphicsUtil.java   View Source Code Vote up 5 votes
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 11
Project: openjdk-jdk10   File: Blink.java   View Source Code Vote up 5 votes
@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 12
Project: OpenJSharp   File: Blink.java   View Source Code Vote up 5 votes
@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 13
Project: incubator-netbeans   File: SwitcherTable.java   View Source Code Vote up 5 votes
/**
 * Calculate the height of rows based on the current font.  This is done
 * when the first paint occurs, to ensure that a valid Graphics object is
 * available.
 *
 * @since 1.25
 */
private void calcRowHeight(Graphics g) {
    Font f = getFont();
    FontMetrics fm = g.getFontMetrics(f);
    // As icons are displayed use maximum from font and icon height
    int rowHeight = Math.max(fm.getHeight(), 16) + 4;
    needCalcRowHeight = false;
    setRowHeight(rowHeight);
}
 
Example 14
Project: JDigitalSimulator   File: HalfAdder.java   View Source Code Vote up 5 votes
@Override public void paint(Graphics graphics) {
	graphics.setColor(Color.BLACK);
	graphics.setFont(graphics.getFont().deriveFont(8f));
	int top = size.height/4, height=graphics.getFontMetrics().getAscent()/2;
	graphics.drawRect(5, 0, size.width-10, size.height);
	graphics.drawString("A", 10, top+height);
	graphics.drawString("B", 10, top*3+height);
	graphics.drawString("S", size.width-15, top+height);
	graphics.drawString("C", size.width-15, top*3+height);
	graphics.setFont(graphics.getFont().deriveFont(Font.BOLD, 15f));
	FontMetrics metrics = graphics.getFontMetrics();
	graphics.drawString("HA", size.width/2-metrics.stringWidth("HA")/2,
			size.height/2+metrics.getAscent()/3);
	ContactUtilities.paintSolderingJoints(graphics, contacts);
}
 
Example 15
Project: incubator-netbeans   File: LineNumbersActionsBar.java   View Source Code Vote up 5 votes
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 16
Project: java-course   File: BarChartComponent.java   View Source Code Vote up 5 votes
/**
 * Calculates max number width for y-axis numeration.
 * 
 * @param g
 *            The {@link Graphics} object.
 * @return Maximum number width.
 */
private int getNumberWidthY(Graphics g) {
    FontMetrics fm = g.getFontMetrics();

    int dimension = 0;
    int yValueStart = chart.getyMin();
    int yValueEnd = chart.getyMax();
    int yValue = Math.max(Math.abs(yValueEnd), Math.abs(yValueStart));

    int width = fm.stringWidth(Integer.toString(yValue));
    dimension = Math.max(width, dimension);

    return dimension;
}
 
Example 17
Project: Logisim   File: Print.java   View Source Code Vote up 4 votes
@Override
public int print(Graphics base, PageFormat format, int pageIndex) {
	if (pageIndex >= circuits.size())
		return Printable.NO_SUCH_PAGE;

	Circuit circ = circuits.get(pageIndex);
	CircuitState circState = proj.getCircuitState(circ);
	Graphics g = base.create();
	Graphics2D g2 = g instanceof Graphics2D ? (Graphics2D) g : null;
	FontMetrics fm = g.getFontMetrics();
	String head = (header != null && !header.equals(""))
			? format(header, pageIndex + 1, circuits.size(), circ.getName())
			: null;
	int headHeight = (head == null ? 0 : fm.getHeight());

	// Compute image size
	double imWidth = format.getImageableWidth();
	double imHeight = format.getImageableHeight();

	// Correct coordinate system for page, including
	// translation and possible rotation.
	Bounds bds = circ.getBounds(g).expand(4);
	double scale = Math.min(imWidth / bds.getWidth(), (imHeight - headHeight) / bds.getHeight());
	if (g2 != null) {
		g2.translate(format.getImageableX(), format.getImageableY());
		if (rotateToFit && scale < 1.0 / 1.1) {
			double scale2 = Math.min(imHeight / bds.getWidth(), (imWidth - headHeight) / bds.getHeight());
			if (scale2 >= scale * 1.1) { // will rotate
				scale = scale2;
				if (imHeight > imWidth) { // portrait -> landscape
					g2.translate(0, imHeight);
					g2.rotate(-Math.PI / 2);
				} else { // landscape -> portrait
					g2.translate(imWidth, 0);
					g2.rotate(Math.PI / 2);
				}
				double t = imHeight;
				imHeight = imWidth;
				imWidth = t;
			}
		}
	}

	// Draw the header line if appropriate
	if (head != null) {
		g.drawString(head, (int) Math.round((imWidth - fm.stringWidth(head)) / 2), fm.getAscent());
		if (g2 != null) {
			imHeight -= headHeight;
			g2.translate(0, headHeight);
		}
	}

	// Now change coordinate system for circuit, including
	// translation and possible scaling
	if (g2 != null) {
		if (scale < 1.0) {
			g2.scale(scale, scale);
			imWidth /= scale;
			imHeight /= scale;
		}
		double dx = Math.max(0.0, (imWidth - bds.getWidth()) / 2);
		g2.translate(-bds.getX() + dx, -bds.getY());
	}

	// Ensure that the circuit is eligible to be drawn
	Rectangle clip = g.getClipBounds();
	clip.add(bds.getX(), bds.getY());
	clip.add(bds.getX() + bds.getWidth(), bds.getY() + bds.getHeight());
	g.setClip(clip);

	// And finally draw the circuit onto the page
	ComponentDrawContext context = new ComponentDrawContext(proj.getFrame().getCanvas(), circ, circState, base,
			g, printerView);
	Collection<Component> noComps = Collections.emptySet();
	circ.draw(context, noComps);
	g.dispose();
	return Printable.PAGE_EXISTS;
}
 
Example 18
Project: incubator-netbeans   File: TableColumnModelEditor.java   View Source Code Vote up 4 votes
@Override
public void paintValue(Graphics g, Rectangle rectangle) {
    String msg = NbBundle.getMessage(TableColumnModelEditor.class, "TableColumnModelEditor_TableColumnModel"); // NOI18N
    FontMetrics fm = g.getFontMetrics();
    g.drawString(msg, rectangle.x, rectangle.y + (rectangle.height - fm.getHeight())/2 + fm.getAscent());
}
 
Example 19
Project: incubator-netbeans   File: TreeModelEditor.java   View Source Code Vote up 4 votes
@Override
public void paintValue(Graphics g, Rectangle rectangle) {
    String msg = NbBundle.getMessage(TreeModelEditor.class, "MSG_TreeModel"); // NOI18N
    FontMetrics fm = g.getFontMetrics();
    g.drawString(msg, rectangle.x, rectangle.y + (rectangle.height - fm.getHeight())/2 + fm.getAscent());
}
 
Example 20
Project: Logisim   File: TextField.java   View Source Code Vote up 4 votes
public void draw(Graphics g) {
	Font oldFont = g.getFont();
	Color oldColor = g.getColor();
	if (font != null)
		g.setFont(font);
	if (color != null)
		g.setColor(color);
	int x = this.x;
	int y = this.y;
	FontMetrics fm = g.getFontMetrics();
	int width = fm.stringWidth(text);
	int ascent = fm.getAscent();
	int descent = fm.getDescent();
	switch (halign) {
	case TextField.H_CENTER:
		x -= width / 2;
		break;
	case TextField.H_RIGHT:
		x -= width;
		break;
	default:
		break;
	}
	switch (valign) {
	case TextField.V_TOP:
		y += ascent;
		break;
	case TextField.V_CENTER:
		y += ascent / 2;
		break;
	case TextField.V_CENTER_OVERALL:
		y += (ascent - descent) / 2;
		break;
	case TextField.V_BOTTOM:
		y -= descent;
		break;
	default:
		break;
	}
	g.drawString(text, x, y);
	g.setFont(oldFont);
	g.setColor(oldColor);
}