Java Notes



The java.awt.Font class is used to create Font objects to set the font for drawing text, labels, text fields, buttons, etc.

Generic Font Names

There are three logical/generic font names. Java will select a font in the system that matches the general characteristics of the logical font.

serifThis text is in a serif font. Often used for blocks of text (eg, Times).
sansserifThis text is in a SansSerif font. Often used for titles (eg, Arial or Helvetica).
monospacedThis text is in a Monospaced font, often used for computer text (eg, Courier).

You can also get a list of the system fonts on the host computer. See below.


Font f = new Font(name, style, size);

String nameint styleint size

or a system font.
Integer point size -- typically in range 10-48.


JButton b = new JButton("OK");
b.setFont(new Font("sansserif", Font.BOLD, 32));

Available system fonts

For maximum portability, use the generic font names, but you can use any font installed in the system. It is suggested to use a font family name, and create the font from that, but you can also use the fonts directly. You can get an array of all available font family names or all fonts.

// Font info is obtained from the current graphics environment.
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();

//--- Get an array of font names (smaller than the number of fonts)
String[] fontNames = ge.getAvailableFontFamilyNames();

//--- Get an array of fonts.  It's preferable to use the names above.
Font[] allFonts = ge.getAllFonts();

Using Fonts for Graphics

Font f;
f = new Font(String name, int style, int size);	// creates a new font

name is "Serif", "SansSerif", or "Monospaced", or a font on the system. style is Font.PLAIN. Font.BOLD, Font.ITALIC, or Font.BOLD+Font.ITALIC. size is the point size, typically in the range 8-48.


Font big = new Font("SansSerif", Font.Bold, 48);
. . .
g.drawString("Greetings Earthling");

Unicode fonts

If you're running a recent version of Windows, you probably already have a Unicode font installed, Arial Unicode MS, which is a very extensive Unicode font.