如果您想在应用程序中使用自定义字体(并非在所有操作系统上都可用),您需要在 .jar 文件中包含字体文件(otf、ttf 等),然后您可以使用通过此处描述的方法在您的应用程序中使用字体:
http://download.oracle.com/javase/6/docs/api/java/awt/Font.html#createFont%28int,%20java.io.File%29
示例代码来自(感谢评论者);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf")));
如果您不确定如何从 .jar 中提取文件,这是我之前在 SO 上分享过的一种方法;
/**
* This method is responsible for extracting resource files from within the .jar to the temporary directory.
* @param filePath The filepath relative to the 'Resources/' directory within the .jar from which to extract the file.
* @return A file object to the extracted file
**/
public File extract(String filePath)
{
try
{
File f = File.createTempFile(filePath, null);
FileOutputStream resourceOS = new FileOutputStream(f);
byte[] byteArray = new byte[1024];
int i;
InputStream classIS = getClass().getClassLoader().getResourceAsStream("Resources/"+filePath);
//While the input stream has bytes
while ((i = classIS.read(byteArray)) > 0)
{
//Write the bytes to the output stream
resourceOS.write(byteArray, 0, i);
}
//Close streams to prevent errors
classIS.close();
resourceOS.close();
return f;
}
catch (Exception e)
{
System.out.println("An error has occurred while extracting a resource. This may mean the program is missing functionality, please contact the developer.\nError Description:\n"+e.getMessage());
return null;
}
}