我正在尝试在我的程序中将自定义字体(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;
}
}
答案 0 :(得分:11)
首先获得URL
Font
。然后做这样的事情。
'Airacobra Condensed'字体可从Download Free Fonts获得。
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));
}
}
好的,这很有趣,但这个字体实际上是什么样的?
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);
}
}
答案 1 :(得分:5)
Font
单独重复加载新的JLabel
装置
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;
}
}
Font
(s)为Local variable
(s)并仅更改jLabel3.setFont(myFont)
,或注册新字体(see link from @StanislavLs comment)例如
InputStream myFont = OptionsValues.class.getResourceAsStream(
"resources/bilboregular.ttf");