madbuggerswall
madbuggerswall

Reputation: 101

Setting a custom font to a JLabel

I'm doing a simple Pong game and wanted to add an 8-Bit font but can not figure how. This is the method I used for JLabels:

public void drawScore()
{
    player1 = "Player 1";
    player2 = "Player 2";


    JLabel leftScore = new JLabel(player1);
    JLabel rightScore = new JLabel(player2);

    leftScore.setForeground(Color.white);
    rightScore.setForeground(Color.white);

    leftScore.setLocation(20, 0);
    rightScore.setLocation(730, 0);

    leftScore.setSize(100, 40);
    rightScore.setSize(100, 40);

    add(leftScore);
    add(rightScore);
}

I tried solutions which I found on here and other web-sites and they didn't work out well either. There is a .TTF file in a folder called 'assets' -which I created- in Java Project Folder named Pong. It would be perfect if the right code not include try and catch blocks.

Upvotes: 0

Views: 1192

Answers (2)

zediogoviana
zediogoviana

Reputation: 305

Please try this:

try {
    InputStream is = YourClass.class.getResourceAsStream("path/to/font");
    Font font = Font.createFont(Font.TRUETYPE_FONT, is); 
    Font sizedFont = font.deriveFont(18f);
    jLabel.setFont(sizedFont);

} catch (Exception ex) {
    System.err.println("Not loaded");}

After you load the font you need to set a size to it!

You will have to use try/catch blocks to do this.

Upvotes: 0

Arrem
Arrem

Reputation: 1023

private static Font fontAwesome;

static {
    try (InputStream in = YOURCLASS.class.getClassLoader().getResourceAsStream("assets/fontawesome-webfont.ttf")) {
        fontAwesome = Font.createFont(Font.TRUETYPE_FONT, in);
    } catch (FontFormatException | IOException e) {
        e.printStackTrace();
    }
}

Here's an example with fontawesome. Paste that at the top of your class and then simply use leftScore.setFont(fontAwesome); to set the font.

Unfortunately you're going to need the try/catches. Note that the multicatch block might not work depending on your language level. If it doesn't just split them into two catch blocks.

Upvotes: 1

Related Questions