Search code examples
javafontsfont-sizeslick2d

Changing Default Font in Slick Graphics API


I am attempting to change the default font for the Slick Graphics API to simply draw the title of a game I'm writing, but I can't seem to get it to work (it doesn't draw anything, just leaving the screen blank). I want to use one of the standard Java fonts (Verdana).

Here is the code I am using to set the font:

import java.awt.Font;

import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.UnicodeFont;

public class Controller extends BasicGame {
UnicodeFont uFont;

@Override
public void render(GameContainer container, Graphics g) throws SlickException {
    g.setFont(uFont);
    g.setColor(Color.white);
    g.drawString("Hello World!", 50, 50);
}

@Override
public void init(GameContainer container) throws SlickException {
    //Set font
    Font font = new Font("Serif", Font.PLAIN, 20);
    uFont = new UnicodeFont(font, font.getSize(), font.isBold(), font.isItalic());
}

/**
 * @param args
 * @throws SlickException 
 */
public static void main(String[] args) throws SlickException {
    //Set up application
    Controller c = new Controller("Tetris");
    AppGameContainer app = new AppGameContainer(c);
    app.setDisplayMode(500, 800, false);

    //Start application
    app.start();
}
}

After numerous attempts myself, I'm using the code found at the bottom of this website:

http://slick.javaunlimited.net/viewtopic.php?t=3508

My question is: how can I change the default font in Slick, and draw text in that font to the screen for the title of my game.


Solution

  • Slick-Util uses Java's built in Font support to load the fonts.You can use either the default built in java fonts or load external ttf files.

    The fonts are stored and drawn through slick's TrueTypeFont class.

    See this code from ninjacave:

    TrueTypeFont font;
    TrueTypeFont font2;
    
    public void init() {
        // load a default java font
        Font awtFont = new Font("Times New Roman", Font.BOLD, 24);
        font = new TrueTypeFont(awtFont, false);
    
        // load font from a .ttf file
        try {
            InputStream inputStream = ResourceLoader.getResourceAsStream("myfont.ttf");
    
            Font awtFont2 = Font.createFont(Font.TRUETYPE_FONT, inputStream);
            awtFont2 = awtFont2.deriveFont(24f); // set font size
            font2 = new TrueTypeFont(awtFont2, false);
    
        } catch (Exception e) {
            e.printStackTrace();
        }   
    }
    

    For further detail look at these sites:

    http://ninjacave.com/slickutil1