使用JLabel的自定义字体 [英] Using a custom font for a JLabel

查看:363
本文介绍了使用JLabel的自定义字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的JFrame中使用特殊的字体,但是我遇到了问题。我有一个像这样定义的JLabel:

I'm trying to use a special font in my JFrame, but I'm running into problems. I have a JLabel defined like this:

private JLabel lab = new JLabel("Text");

我有一个名为CUSTOMFONT-MEDIUM.TTF(TrueType字体)的文件,

and I have a file called CUSTOMFONT-MEDIUM.TTF (TrueType font) but after writing the following:

    try {
    lab.setFont(Font.createFont(Font.TRUETYPE_FONT, getClass().getResource("/CUSTOMFONT-MEDIUM.TTF").openStream()));
    } catch(IOException ex){
    //exception handled here I suppose  
    } catch(FontFormatException ex2) {
    //same here
    }

代码编译和一切工作正确,除了实验室没有显示,所以没有文字。我想这是因为我从来没有指定字体大小应该是什么,但是我所做的任何尝试都失败了。有人可以帮助我吗?

the code compiles and the everything works right except that "lab" is not displayed so there is no text. I suppose it is because I never specified what the font size should be, but any attempt I have made to do that fails. Can someone help me out here?

推荐答案

您创建的字体必须首先在 GraphicsEnvironment 可被所有人访问,并获得字体的大小:

The Font you created has to be registered first in the GraphicsEnvironment to be accessible to all and derive the size of the font:

Font font = Font.createFont(Font.TRUETYPE_FONT, getClass().getResource("/CUSTOMFONT-MEDIUM.TTF").openStream());   

GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment();
genv.registerFont(font);
// makesure to derive the size
font = font.deriveFont(12f);

这篇关于使用JLabel的自定义字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆