Hello everyone I am having some trouble loading custom fonts into Java.
public class CustomFonts extends JPanel {
public static void loadFont() throws FontFormatException, IOException {
String fontFileName = "stocky.ttf";
InputStream is = CustomFonts.class.getClassLoader()
.getResourceAsStream(fontFileName);
Font ttfBase = Font.createFont(Font.TRUETYPE_FONT, is);
Font ttfReal = ttfBase.deriveFont(Font.PLAIN, 24);
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
ge.registerFont(ttfReal);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("Blach Blach Blach");
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
try {
loadFont();
} catch (FontFormatException | IOException e) {
e.printStackTrace();
}
JLabel fontF = new JLabel("Testing 1, 2, 3");
fontF.setFont(new Font("ttfReal", Font.PLAIN, 20));
frame.add(fontF);
}
}
When I run the code the font just seems to be the default one. I have loaded the ttf file into the project folder of Eclipse but do I have to give a explicit route to the file? I am trying to understand fonts through this basic program because I am trying to load it into a bigger program.