Importing Font to GUI

后端 未结 3 1219
[愿得一人]
[愿得一人] 2021-01-24 07:54

I am trying to change the font for my GUI besides the basic 5 that swing seems to come with. How to import fonts and actually use them in my code?

3条回答
  •  鱼传尺愫
    2021-01-24 08:30

    There are usually more than 5 available by default, but they change from system to system. This answer examines both the existing fonts, as well as how to load & register new fonts.

    It uses the 'Airacobra Condensed' font available from Download Free Fonts (obtained by hot-link URL). A font that is in the Jar of your app. is also accessible by URL.

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

    OK, that was fun, but what does this font actually look like?

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

提交回复
热议问题