JButton文本如何使用不同的自定义字体?

3
现在,我知道在JButton文本中可以使用不同的字体族。就像下面这样。
JButton button = new JButton("<html><font face=Arial>Hello </font><font face=Verdana>World</font></html>");

看起来是这样的。用Arial字体写“Hello”,Verdana字体写“World”。

enter image description here

但是,如果我想要一个单词具有我使用Font.createFont()方法创建的字体呢?我想过,这样做应该可以。

Font myFont = createMyFont();
JButton button = new JButton("<html><font face=MyFont>Hello </font>World</html>");

这个问题的意义在于,我正在创建一个多语言软件,其中一个 JButton 中有两种字体。

因此,我希望我的 JButton 看起来像这样:

enter image description here

但是,实际上看起来像这样:

enter image description here


Javadoc提到在使用Font.createFont()创建字体后,应该使用Font.registerFont() - Extreme Coders
尝试注册字体:`GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); ge.registerFont(myFont);` - Maxim Shoustin
那么,我应该用什么名称来称呼它?使用它的文件名吗? - Akshat
是的,它正在工作。但是,我不得不从其字体文件名“Devlys_010”中删除“_”,并像这样编码<font face="Devlys 010">ABC</font>。 - Akshat
我认为,有人应该将其作为答案。这样可以帮助他人。 - Akshat
显示剩余2条评论
1个回答

2

使用以下代码注册自定义字体:

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment()
ge.registerFont(myFont);

接下来,提供文件名,例如:

      URL fontUrl;
        try {
            fontUrl = new URL("http://www.webpagepublicity.com/" +
                    "free-fonts/a/Airacobra%20Condensed.ttf"); // dummy font 

            Font myFont = Font.createFont(Font.TRUETYPE_FONT, fontUrl.openStream());
            myFont = myFont.deriveFont(Font.PLAIN,20);
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            ge.registerFont(myFont);


            button.setText("<html><font face='Airacobra Condensed'>Hello </font>World</html>");

        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (FontFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

在Windows上,可以右键单击字体文件并选择“属性”->“详细信息”,然后就可以获取文件名。例如:FontAwesome Regular。
示例图像如下:

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接