1

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 you know where I can find another font that will be monospace and lcd (I wan to type only digitals)?

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
javaAmator
  • 13
  • 1
  • 4
  • 1
    Welcome to SO, javaAmator! Unfortunately, even though you're doing a project in Java, this question isn't really suitable for SO because the act of finding a font isn't programming-related. I suggest you ask over at http://www.doctype.com/ where there are more design-oriented folks. If you ever have questions about stuff like algorithms, programming language syntax or bugs in code, though, we'll be happy to help! – Pops May 08 '10 at 16:10
  • @Lord Torgamus: I agree with your comment, but I proposed an answer to the drawing question. Sorry if I preempted your offer to help. I usually stick with the platform-specified font families, so I'd welcome any additions or corrections on how to select alternate fonts. – trashgod May 08 '10 at 17:30

1 Answers1

2

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.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045