Reputation: 36299
I am trying to display a custom font within a JLabel, but when I create it, it displays as very tiny text. I cant even tell if it is using the font that I specified, because the text is so small. Here is the font that I used. So what am I doing that is causing the font to be so small?
package sscce;
import java.awt.Font;
import java.awt.FontFormatException;
import java.io.File;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main extends JFrame{
public Main(){
this.setSize(300, 300);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GameFont fnt = new GameFont("/home/ryan/Documents/Java/Space Shooters/src/media/fonts/future.ttf", 20);
Label lbl = fnt.createText("Level 1 asdf sadf saf saf sf ");
this.add(lbl);
}
public static void main(String[] args){
Main run = new Main();
}
public class GameFont{
protected Font font;
public GameFont(String filename, int fontSize){
try{
File fontFile = new File(filename);
font = Font.createFont(Font.TRUETYPE_FONT, fontFile);
font.deriveFont(fontSize);
}catch(FontFormatException | IOException e){
}
}
public Label createText(String text){
Label lbl = new Label(font);
lbl.setText(text);
return lbl;
}
}
public class Label extends JLabel{
public Label(Font font){
this.setFont(font);
}
}
}
Upvotes: 2
Views: 1021
Reputation: 285405
Please look again at the Font API, deriveFont(...) method. You want to pass in a float, not an int for the size, since if an int parameter is passed in, the method will expect this to mean to set a Font's style (bold, italics, underlined), not its size. You also need to use the Font returned by the deriveFont(...)
method.
So change this:
public GameFont(String filename, int fontSize){
try{
File fontFile = new File(filename);
font = Font.createFont(Font.TRUETYPE_FONT, fontFile);
font.deriveFont(fontSize);
}catch(FontFormatException | IOException e){
}
}
to this:
public GameFont(String filename, float fontSize){
try{
File fontFile = new File(filename);
font = Font.createFont(Font.TRUETYPE_FONT, fontFile);
font = font.deriveFont(fontSize);
}catch(FontFormatException | IOException e){
e.printStackTrace(); // ****
}
}
Also, never ever ignore exceptions like you're doing!
Upvotes: 3