The Coder's Handbook
Fonts
CREATING AND SETTING FONTS
For more detailed information, look at the Font and Graphics class in the Slick 2D Javadoc
Another solution involves using Unicode Fonts. Here is a guide created by one of my students. See Unicode Font Documentation.
Creating a Font
You need to create a font before you use it.
Make a method that loads all your fonts.
In a large package, this could be its own class.
It's okay to make them public and static so they can be accessed everywhere.
Slick Fonts are wrapped around the basic Java Font class.
This means you'll need two imports.
import java.awt.Font;
import org.newdawn.slick.TrueTypeFont;
public class Game
{
public static TrueTypeFont textFont;
public static TrueTypeFont headingFont;
public static void loadFonts()
{
textFont = new TrueTypeFont(new Font("Arial", Font.PLAIN, 14), false);
headingFont= new TrueTypeFont(new Font("OCR A Extended", Font.BOLD, 64), false);
}
}
Using a Font by Setting
In your code right before drawing text, you'll need to use the setFont method from the Graphics class.
public void render(Graphics g)
{
g.setFont(Game.textFont);
g.drawString("Hello", 50, 50);
}
Using a Font Directly
You can also draw a single message directly in a Font by calling the Font's drawString method.
public void render(Graphics g)
{
Game.textFont.drawString(50, 50, "Hello");
}
TEXT ALIGNMENT
How To Center Text
Slick does not have built-in functions to center your text on vertically or horizonatally, but you can build your own.
The Font class has two methods: getWidth(String s) and getHeight(String s) which tell you how wide or tall in pixels the specified String would be in that font. From this you can use math to center your String.
int scoreX = 500;
int scoreY = 200;
public void render(Graphics g)
{
String message = "Score: " + getUserScore();
int w = Game.textFont.getWidth(message);
g.setFont(Game.textFont);
g.drawString(message, scoreX - w / 2, scoreY);
}