开发者

Java monospace draw string

How can I draw a String in Java (using Graphics2d) in monospace mode? I have a font that looks like LCD screen font, and I want to draw something like LCD label.

I am using Digital 7 Mono font.

Do yo开发者_运维技巧u know where I can find another font that will be monospace and lcd (I wan to type only digitals)?


How can I draw a String in Java (using Graphics2d) in monospace mode?

The essential method needed to render text is drawString(), as outlined below. There is no "monospace mode", per se, but even proportionally spaced fonts typically use a constant width for digit glyphs .

private static final Font font = new Font("Monospaced", Font.PLAIN, 32);
private static final String s = "12:34";
...
@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setFont(font);
    int xx = this.getWidth();
    int yy = this.getHeight();
    int w2 = g.getFontMetrics().stringWidth(s) / 2;
    int h2 = g.getFontMetrics().getDescent();
    g.setColor(Color.green);
    g.drawString(s, xx / 2 - w2, yy / 2 + h2);
}

There's a complete example here, and you can extend a suitable JComponent to control positioning using a layout manager, as seen here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜