Write text on the screen with LWJGL

julian picture julian · Oct 4, 2013 · Viewed 10.5k times · Source

I want to write text on the screen for my game, for things like fps, random text for items and stuff. How can I write that text?

Is it possible without the Basic Game class? Isn't there a command like this g.drawString("Hello World", 100, 100);?

Answer

The Guy with The Hat picture The Guy with The Hat · Oct 4, 2013

Update: this answer is now outdated, and does not work at all with the latest versions of LWJGL. Until I update this answer fully, I recommend that you look here: http://www.java-gaming.org/topics/lwjgl-stb-bindings/36153/view.html


You could use the TrueType fonts feature in the Slick-util library.

Using a common font is easy, just create the font like this:

TrueTypeFont font;
Font awtFont = new Font("Times New Roman", Font.BOLD, 24); //name, style (PLAIN, BOLD, or ITALIC), size
font = new TrueTypeFont(awtFont, false); //base Font, anti-aliasing true/false

If you want to load the font from a .ttf file, it's a little more tricky:

try {
    InputStream inputStream = ResourceLoader.getResourceAsStream("myfont.ttf");

    Font awtFont = Font.createFont(Font.TRUETYPE_FONT, inputStream);
    awtFont = awtFont.deriveFont(24f); // set font size
    font = new TrueTypeFont(awtFont, false);

} catch (Exception e) {
    e.printStackTrace();
}

After you have successfully created a TrueTypeFont, you can draw it like this:

font.drawString(100, 50, "ABC123", Color.yellow); //x, y, string to draw, color

For more information, you can look at the documentation for TrueTypeFont and java.awt.Font, and the Slick-Util tutorial I got most of this code from.