nico.user
nico.user

Reputation: 483

How to display a Custom Font Text in a JFrame in java?

I have being trying to display a phrase with a custom font onto a JFrame but I only end up with the text without the font. When I compile the following code:

import java.awt.*;
import javax.swing.*;
import java.awt.image.*;
import java.awt.Font.*;

public class JavaPractice{
  public static void main(String[]args){
    JFrame frame = new JFrame("Java Practice!");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(label);
    frame.pack();
    frame.getContentPane().setBackground(Color.decode("#101010"));
    frame.setSize(720,480);
    frame.setResizable(false);
    frame.setVisible(true);
    JLabel label = new JLabel("Press Enter To Continue");
    Font font = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("PixelFont.ttf"));
    label.setFont(font.deriveFont(Font.BOLD, 12f));
  }
}

I get feedback from the compiler saying that getClass() is not a non-static method and cannot be referenced from a static context.

It also says that it cannot find the symbol frame.add(label);

Please be specific in your answer since I am not that advanced in Java.

Upvotes: 1

Views: 6327

Answers (1)

MC10
MC10

Reputation: 572

I've changed your code based on the things we pointed out in the comments. Where is your font file located?

import java.awt.*;
import javax.swing.*;
import java.awt.image.*;
import java.awt.Font.*;

public class JavaPractice{
    public static void main(String[]args){
        JFrame frame = new JFrame("Java Practice!");
        JLabel label = new JLabel("Press Enter To Continue");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(label);
        frame.pack();
        frame.getContentPane().setBackground(Color.decode("#101010"));
        frame.setSize(720,480);
        frame.setResizable(false);
        frame.setVisible(true);
        try{
            Font font = Font.createFont(Font.TRUETYPE_FONT, JavaPractice.class.getResourceAsStream("PixelFont.ttf"));
            label.setFont(font.deriveFont(Font.BOLD, 12f));
        }
        catch(Exception e){}
    }
}

The result currently is: Output

Upvotes: 4

Related Questions