【问题标题】:How to apply .ttc to a Font in Java awt如何将 .ttc 应用于 Java awt 中的字体
【发布时间】:2022-01-04 12:58:22
【问题描述】:

我试图在 IntelliJ IDEA 中使用 java.io.InputStream 读取 .ttc 文件,但失败了。

这是我的代码:

InputStream inputStream = getClass().getResourceAsStream("Dependencies\\msjh.ttc");
Font font;
try
{
    if (inputStream == null)
        throw new IOException();
    font = Font.createFont(Font.TRUETYPE_FONT, inputStream).deriveFont(Font.PLAIN);
}
catch (IOException | FontFormatException exception)
{
    font = new Font("Microsoft JhengHei UI", Font.PLAIN, 16);
}

无论我如何尝试,条件if (inputStream == null)总是为真,并且会抛出IOException。

但是类似的设置窗口图标的方法是有效的:

Frame frame = new Frame("Window");
frame.setIconImage(Toolkit.getDefaultToolkit().getImage("Dependencies\\icon.png"));

这是我文件中的路径:

IdeaProjects\Project\Dependencies\msjh.ttc (font file)
IdeaProjects\Project\Dependencies\icon.png (image file)
IdeaProjects\Project\src\bin_gen\Main.java (source code)

还有一个虚拟机选项:-Dfile.encoding=MS950

那个 .ttc 文件是从 C:\Windows\Fonts\Microsoft JhengHei UI 复制的。我正在尝试这个,因为font = new Font("Microsoft JhengHei UI", Font.PLAIN, 16); 似乎不起作用(窗口上显示的字体仍然是默认字体)。

【问题讨论】:

    标签: java fonts awt inputstream embedded-resource


    【解决方案1】:

    我建议使用getResource 而不是getResourceAsStream。他们遵循的规则略有不同,我很理解前者的规则。

    如果字体在 IDE 创建的 Jar 中,它将位于 /Dependencies/msjh.ttc

    请注意两个单独的正斜杠 (/),而不是类似文件的反斜杠 (\\)。该反斜杠仅适用于文件,并且仅适用于 Windows。 getResource 需要的是一个直接来自项目或 jar 根目录或相对于调用它的类的资源路径。 / 前缀告诉 JRE 从类路径的根目录中查找资源,而不是相对于调用类。

    也不要使用getImage("Dependencies\\icon.png")。这将假定该字符串表示一个文件路径,这在部署项目时将不起作用。也可以使用getResource

    【讨论】:

      猜你喜欢
      • 2020-05-06
      • 2014-09-18
      • 2016-01-07
      • 2018-08-15
      • 2013-05-25
      • 2013-03-05
      • 2013-07-06
      • 2011-11-27
      • 2019-09-10
      相关资源
      最近更新 更多