如何在不同的电脑上使用java项目中下载的字体



我下载了Font"Retro Gaming;(https://www.dafont.com/retro-gaming.font)在我的Java项目中使用它。这个项目需要在我运行的每台机器上运行。我的问题是:如何或在哪里放置字体,以便所有计算机(即使没有安装(都可以使用它?我认为gradle可能是一个很好的解决方案,但我在互联网上一无所获。

代码示例为:

public PlayerOneLabel() {
this.setText("PLAYER 1");
this.setForeground(Color.white);
this.setFont(new Font("Retro Gaming", Font.BOLD, CenterOnDefaultScreen.center().height*2/100));
}

这显然只在已经安装了字体的电脑上运行。

将字体文件保存到您喜欢的位置。。。将其与其他游戏文件放在一起,或者将其放在资源文件夹中。如果只是为了你的比赛,它不需要去特别的地方。您可以使用以下方法在需要时加载字体:

/**
* Loads a Font file and returns it as a Font Object. This method does try to 
* utilize the proper Font Type Resource (TrueType or Type1) but will default 
* to TrueType if the resource type can not be established.
* 
* @param fontFilePath (String) Full path and file name of the font to load.<br>
* 
* @param fontStyle (Integer) The Font Style to use for the loaded font, for 
* example:<pre>
* 
*      Font.PLAIN
*      Font.BOLD
*      Font.ITALIC
*      Font.BOLDITALIC</pre>
* 
* @param fontSize (Integer) The desired size of font.<br>
* 
* @return (Font) A Font Object
*/
public Font loadFont(String fontFilePath, int fontStyle, int fontSize) {
Font font = null;
int fontTypeResource = Font.TRUETYPE_FONT;
if ((fontFilePath == null || fontFilePath.isEmpty()) || fontSize < 1) {
throw new IllegalArgumentException("loadFont() Method Error! Arguments "
+ "passed to this method must contain a file path OR a numerical "
+ "value other than 0!" + System.lineSeparator());
}
String fileExt = (fontFilePath.contains(".") ? fontFilePath.substring(fontFilePath.lastIndexOf(".") + 1) : "");
if (fontFilePath.isEmpty()) {
throw new IllegalArgumentException("loadFont() Method Error! An illegal "
+ "font file has been passed to this method (no file name "
+ "extension)!" + System.lineSeparator());
}

switch (fileExt.toLowerCase()) {
case "fot":
case "t2":
case "otf":
case "ttf":
fontTypeResource = Font.TRUETYPE_FONT;
break;
// PostScript/Adobe
case "lwfn":
case "pfa":
case "pfb":
case "pdm":
fontTypeResource = Font.TYPE1_FONT;
break;
default:
fontTypeResource = Font.TRUETYPE_FONT;
}

try {
font = Font.createFont(fontTypeResource, new FileInputStream(
new File(fontFilePath))).deriveFont(fontStyle, fontSize);
}
catch (FileNotFoundException ex) {
Logger.getLogger("loadFont()").log(Level.SEVERE, null, ex);
}
catch (FontFormatException | IOException ex) {
Logger.getLogger("loadFont()").log(Level.SEVERE, null, ex);
}
return font;
}

以及如何使用:

JLabel jLabel_1 = new JLabel("This is my Label Caption");
/* Assumes the .ttf file in within the application's project 
directory. Use a getResource() mechanism when loading from
a resource directory.                           */
Font gameFont = loadFont("Retro Gaming.ttf", Font.BOLD, 18);
jLabel_1.setFont(gameFont);

最新更新