设置自定义字体(Setting custom font)

2019-06-21 14:25发布

我想自定义字体(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;
    }
}

Answer 1:

首先获得一个URLFont 。 然后做这样的事情。

“Airacobra简明”的字体可从下载免费字体 。

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));
    }
}

OK,这很有趣,但是这是什么字体实际上是什么样子?

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);
    }
}


Answer 2:

  • 不加载一个新的Font屡中,对于每个JLabel separatelly

手段

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)或注册一个新的字体( 请参阅从@StanislavLs评论链接 )

例如

InputStream myFont = OptionsValues.class.getResourceAsStream(
     "resources/bilboregular.ttf");


文章来源: Setting custom font