Java不能读取字体 [英] Java Can't Read font

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

问题描述

好的,所以我有一个使用自定义字体的问题。基本上我得到一个自定义的字体,我从互联网上下载,并在我的程序中使用它。当我在Eclipse(我使用的编辑器)中运行程序时,一切正常,没有问题。但是,每当我从eclipse中将它导出到一个jar文件,或者尝试从命令提示符运行它,我得到这个非常恼人的错误:

  java.io.IOException:在TowerDefense中无法读取REVOLUTION.ttf 
(位于java.awt.Font.createFont(未知源))
。< init>(TowerDefense.java:55)$我在TowerDefense.main(TowerDefense.java:302)



空指针异常,因为我在哪里使用字体。但我不知道为什么说它不能读取它。这是创建字体的代码:

  try {
revolution = Font.createFont(Font.TRUETYPE_FONT,new文件( REVOLUTION.ttf));
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(revolution);
}
catch(Exception e){
e.printStackTrace();

文件夹布局 $ b TowerDefense

$ s
默认包
TowerDefense.java
Game.java
DragTest.java
JRE系统库
REVOLUTION.ttf
neuropol.ttf


解决方案

您无法使用File API访问JAR的内容。

使用Classloader的 getResourceAsStream 方法加载字体文件。为了实现这个功能,你必须把字体文件放在classpath中。



所以你的代码变成了:

<$ ()。getClassLoader()。getResourceAsStream(REVOLUTION.ttf));

如果字体包含在JAR中的包或文件夹中,则路径会相应地改变。

  getResourceAsStream(com / example / font / REVOLUTION.ttf); //如果字体存在于com.example.font包中


Ok, so I have a problem using a custom font. Basically I get a custom font I downloaded off the internet and use it in my program. When I run the program in Eclipse (the editor I use), everything works fine, and there is no problem. BUT, whenever I export it to a jar from eclipse, or try to run it from the command prompt I get this very annoying error:

java.io.IOException: Can't read REVOLUTION.ttf
    at java.awt.Font.createFont(Unknown Source)
    at TowerDefense.<init>(TowerDefense.java:55)
    at TowerDefense.main(TowerDefense.java:302)

I get that along with a bunch of null pointer exceptions because of where I use the font. But I don't know why it says it can't read it. Here is the code that creates the font:

try {
        revolution = Font.createFont(Font.TRUETYPE_FONT, new File("REVOLUTION.ttf"));
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        ge.registerFont(revolution);
    }
    catch (Exception e) {
        e.printStackTrace();
    }

FOLDER LAYOUT

TowerDefense

src
    default package
        TowerDefense.java
        Game.java
        DragTest.java
JRE System Library
REVOLUTION.ttf
neuropol.ttf

解决方案

You can not access contents of a JAR using File API.

You have to load the font file using Classloader's getResourceAsStream method. For this to work you'll have to put the font file on classpath.

So you code becomes:

revolution = Font.createFont(Font.TRUETYPE_FONT, getClass().getClassLoader().getResourceAsStream("REVOLUTION.ttf"));

If font is included inside a package or folder in JAR, then path would change accordingly.

getResourceAsStream("com/example/font/REVOLUTION.ttf"); // if font is present inside com.example.font package

这篇关于Java不能读取字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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