自定义 JLabel 字体太小



我正在尝试在 JLabel 中显示自定义字体,但是当我创建它时,它显示为非常小的文本。我什至无法判断它是否使用了我指定的字体,因为文本太小了。这是我使用的字体。那么我做了什么导致字体这么小?

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);
        }
    }
}

请再看一下 Font API,deriveFont(...) 方法。您希望传入浮点数,而不是大小的 int,因为如果传入 int 参数,该方法将期望这意味着设置字体的样式(粗体、斜体、下划线),而不是其大小。您还需要使用 deriveFont(...) 方法返回的 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 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(); // ****
        }
    }

此外,永远不要像您一样忽略异常!

最新更新