Re: How to Get a Monospaced Font
In article
<df5fc2e0-7995-4cbc-827f-bdf01f0afb9d@n2g2000pre.googlegroups.com>,
KevinSimonson <kvnsmnsn@hotmail.com> wrote:
Can someone tell me a font I can use that might have a
chance of being monospaced?
Java supports logical fonts having the names Serif, SansSerif,
Monospaced, Dialog, and DialogInput. The logical font names are mapped
to physical fonts by the JRE. As Martin Gregorie suggests, you're
probably looking for Monospaced.
<http://download.oracle.com/javase/6/docs/api/java/awt/Font.html>
Here's a little demo of FontMetrics, "which encapsulates information
about the rendering of a particular font on a particular screen."
<http://download.oracle.com/javase/6/docs/api/java/awt/FontMetrics.html>
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Rectangle;
public class FrameChars extends JPanel {
private static final int W = 640;
private static final int H = 480;
private static Font font = new Font("Monospaced", Font.PLAIN, 32);
private FrameChars() {
setPreferredSize(new Dimension(W, H));
setBackground(Color.black);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
render(g, "abcdefghijklmnopqrstuvwxyz", 32, 2 * H / 5);
render(g, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 32, 3 * H / 5);
}
private void render(Graphics g, String s, int x, int y) {
g.setFont(font);
g.setColor(Color.green);
g.drawString(s, x, y);
g.setColor(Color.blue);
FontMetrics fm = g.getFontMetrics();
Rectangle r = fm.getStringBounds(s, g).getBounds();
g.drawRect(r.x + x, r.y + y, r.width, r.height);
}
public static void main(String[] arguments) {
FrameChars fc = new FrameChars();
JFrame fcFrame = new JFrame("FrameChars");
fcFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fcFrame.getContentPane().add(fc);
fcFrame.pack();
fcFrame.setVisible(true);
}
}
FWIW, I'm wary of relying on font spacing for alignment; that's what
layout managers are for.
--
John B. Matthews
trashgod at gmail dot com
<http://sites.google.com/site/drjohnbmatthews>