Search code examples
javaswingfontsjtextfield

Font displays in text field very small


I have this class, and I am trying to display a custom font in a text field, but but when I run it the font is super tiny like 2px tiny. If i just run font = new Font("sans-serif", Font.PLAIN, 24); it displays just fine at the right font size.

Here is what it looks like:

Small

Here is what it looks like when I only use font = new Font("sans-serif", Font.PLAIN, 24);

Large

What is causing the small text box with a custom font?

public class Search extends JTextField{

    public Search(int width){
        super(width);

        Font font;
        String filename = "/media/fonts/SourceCodePro-Light.ttf";

        try{
            InputStream is = this.getClass().getResourceAsStream(filename);
            font = Font.createFont(Font.TRUETYPE_FONT, is);
            font = font.deriveFont(24);
        }catch(FontFormatException | IOException ex){
            font = new Font("sans-serif", Font.PLAIN, 24);
        }

        this.setFont(font);

    }
}

Solution

  • font.deriveFont has two overloaded forms that can be quite similar. The one taking int sets the font style, the one taking float sets the font size. YOu are invoking the int version instead of the float version. Change 24 to 24.0f, and it will work