使用JLabel的自定义字体

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

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

我有一个名为CUSTOMFONT-MEDIUM.TTF(TrueType字体)的文件,但在写完以下内容之后:

  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 } 

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

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

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

@sasankad大多是正确的(+1)。

创建字体后,其默认大小为1

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

然后,您需要派生所需的字体大小和样式。

 Font biggerFont = font.deriveFont(Font.BOLD, 48f); 

在此处输入图像描述

 import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Font; import java.awt.FontFormatException; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagLayout; import java.io.File; import java.io.IOException; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class TestCustomFont { public static void main(String[] args) { new TestCustomFont(); } public TestCustomFont() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new TestPane()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class TestPane extends JPanel { public TestPane() { setLayout(new GridBagLayout()); try { Font font = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("/Royal Chicken.ttf")); JLabel happy = new JLabel("Happy little Miss Chicken"); happy.setFont(font.deriveFont(Font.BOLD, 48f)); add(happy); } catch (FontFormatException | IOException ex) { ex.printStackTrace(); } } } } 

查看java.awt.Font了解更多详情……

您可能还想查看物理和逻辑字体,字体配置文件