gpt4 book ai didi

java - 设置自定义字体

转载 作者:搜寻专家 更新时间:2023-11-01 01:06:34 24 4
gpt4 key购买 nike

我正在尝试在我的程序中将自定义字体 (bilboregular.ttf) 设置为 2 个 jLabel但是字体没有成功加载。

这里是主要的方法调用:

//this should work if the build is in a jar file, otherwise it'll try to load it directly from the file path (i'm running in netbeans)
if (!setFonts("resources/bilboregular.ttf")) {
System.out.println("=================FAILED FIRST OPTION"); // <<<<<<<< This is being displayed
if(!setFonts(System.getProperty("user.dir")+"/src/resources/bilboregular.ttf")){
System.out.println("=================FAILED SECOND OPTION"); // <<< This is not being displayed
}
}

这是另一种方法:

public boolean setFonts(String s) {
try {
jLabel3.setFont(java.awt.Font.createFont(java.awt.Font.TRUETYPE_FONT, new java.io.File(s)));
jLabel4.setFont(java.awt.Font.createFont(java.awt.Font.TRUETYPE_FONT, new java.io.File(s)));
return true;
} catch (Exception ex) {
return false;
}
}

最佳答案

首先获取字体URL。然后做这样的事情。

'Airacobra Condensed' 字体可从 Download Free Fonts 获得。

Registered Font

import java.awt.*;
import javax.swing.*;
import java.net.URL;

class LoadFont {
public static void main(String[] args) throws Exception {
// This font is < 35Kb.
URL fontUrl = new URL("http://www.webpagepublicity.com/" +
"free-fonts/a/Airacobra%20Condensed.ttf");
Font font = Font.createFont(Font.TRUETYPE_FONT, fontUrl.openStream());
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font);
JList fonts = new JList( ge.getAvailableFontFamilyNames() );
JOptionPane.showMessageDialog(null, new JScrollPane(fonts));
}
}

好吧,这很有趣,但这种字体实际上是什么样子的?

Display Font

import java.awt.*;
import javax.swing.*;
import java.net.URL;

class DisplayFont {
public static void main(String[] args) throws Exception {
URL fontUrl = new URL("http://www.webpagepublicity.com/" +
"free-fonts/a/Airacobra%20Condensed.ttf");
Font font = Font.createFont(Font.TRUETYPE_FONT, fontUrl.openStream());
font = font.deriveFont(Font.PLAIN,20);
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font);

JLabel l = new JLabel(
"The quick brown fox jumped over the lazy dog. 0123456789");
l.setFont(font);
JOptionPane.showMessageDialog(null, l);
}
}

关于java - 设置自定义字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13717481/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com