【问题标题】:How to Embed Font in JavaFX?如何在 JavaFX 中嵌入字体?
【发布时间】:2019-03-15 23:40:33
【问题描述】:

如何在 JavaFX 应用程序中嵌入自定义字体?我尝试制作一个 fonts.mf 文件,并按照下面链接的类似问题的说明进行操作。如果不需要,我不想使用 CSS。我想专注于学习核心 JavaFX 的东西。

这是我一直在搞砸的:

private static Label makeTitle() {
   Label title = new Label("Bandit King");
   Font font = new Font("OldStyle", 40);
   title.setFont(font);

   return title;
}

我的 fonts.mf 文件只包含这一行:

OldStyle = /home/myName/Desktop/My_Java_Projects/Bandit_King/banditKing/OLDSH.TTF

这不是this question 的副本。 Eclipse 说,“CustomFontApp,无法解析为类型”。

【问题讨论】:

  • 您没有显示您尝试加载字体(即Font.loadFont)。 CustomFontApp 是什么?
  • 我不知道 CustomFontApp 是什么,它只是写在我链接的问题中。我以为Font font = new Font("OldStyle", 40); 确实加载了字体。
  • 据我所知,构造函数和工厂方法只是简单地搜索现有字体以获得最佳匹配。在使用之前,您必须使用Font.loadFont@font-face 实际加载任何自定义字体。此外,看起来CustomFontApp 是链接非重复中示例Application 类的名称;你不能在你自己的代码中使用它,除非你也创建了那个类。
  • :/ 抱歉,我应该注意到这一点。我还有一个问题。我似乎无法以同样的方式使用toExternalForm()。 Eclipse 说,“方法 toExternalForm() 没有为 InputStream 类型定义”
  • 发布导致错误的代码。

标签: java eclipse user-interface javafx graphics


【解决方案1】:

我尝试过制作 fonts.mf 文件

你不需要它。

这不是这个问题的重复。 Eclipse 说,“CustomFontApp,无法解析为类型”。

CustomFontApp 只是您链接的答案中使用的类名 - 您的类名显然不同,您应该更改它。

这一行:

Font font = new Font("OldStyle", 40);

只有在您的系统上安装了OldStyle 字体时才会加载它。您使用的不是已安装的字体,而是嵌入的字体,所以这不起作用。

您需要使用Font.loadFont(InputStream, double)Font.loadFont(String, double) 从磁盘加载您的自定义字体:

// use this to load font from your application's resource folder (`res/fonts/OLDSIH.TTF`)
Font font = Font.loadFont(getClass().getResourceAsStream("/fonts/OLDSIH.TTF"), 40);

// or this one to load font from the specified (absolute) path
// (not recommended, use the method above or, at least, change this into relative path):
Font font = Font.loadFont("file:///home/myName/Desktop/My_Java_Projects/Bandit_King/banditKing/OLDSH.TTF", 40);

【讨论】:

  • 我按照你说的做了,但是 Eclipse 用 getClass() 抛出了一个错误,它说:“不能从 Object 类型对非静态方法 getClass() 进行静态引用”。我的代码是Font font = Font.loadFont(getClass().getResourceAsStream("/fonts/OLDSH.TTF"), 40);
  • 那是因为makeTitle方法是static,而getClass()是实例方法,所以没有对象就不能调用。您确实应该将您的代码从 main 移动到 start 方法,但如果您只想快速修复上述问题 - 将 getClass() 更改为 Main.class,其中 Main 是您的主类的名称。
猜你喜欢
  • 2015-07-16
  • 2013-05-27
  • 2020-07-29
  • 1970-01-01
  • 2015-07-26
  • 2013-12-07
  • 2011-05-13
  • 2012-11-22
相关资源
最近更新 更多