如何在 Java Swing 中使用 Wingdings 字体

Roy*_*Roy 4 java swing wingdings

当我尝试使用 Wingdings 字体(或其他符号字体)时,文本显示为矩形而不是正确的文本。如何获得正确的字符显示?

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

public class WingdingsFontDisplay extends JFrame
{
    public static void main(String[] args)
    {
        new WingdingsFontDisplay();
    }

    public WingdingsFontDisplay()
    {
        this.setSize(500,150);
        this.setTitle("Fun with Fonts");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //This shows that I do have "Wingdings" available
        GraphicsEnvironment g;
        g = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String[] fonts = g.getAvailableFontFamilyNames();
        for(String f : fonts)
        {
            System.out.println(f);
        }

        //Displaying text in the Wingdings font shows rectangles
        JLabel wingdingsText = new JLabel("All work and no play makes Jack a dull boy");
        Font f1 = new Font("Wingdings", Font.PLAIN, 14);
        wingdingsText.setFont(f1);
        this.add(wingdingsText, BorderLayout.NORTH);

        //Displaying text in Arial works correctly
        JLabel arialText = new JLabel("All work and no play makes Jack a dull boy");
        Font f2 = new Font("Arial", Font.PLAIN, 14);
        arialText.setFont(f2);
        this.add(arialText, BorderLayout.SOUTH);

        this.setVisible(true);
    }
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*ath 5

您需要为您寻找的符号使用适当的 Unicode 范围。在 Java 中,符号不覆盖在 ASCII 范围内,而是具有自己独特的字符代码。

您可以在http://unicode.org/~asmus/web-wing-ding-ext.pdf 找到对适当符号代码的参考。最常见的符号在 0x2200 和 0x2700 Unicode 范围内。

您的 Java 安装可能包含SymbolTest示例小程序,​​这使得使用可用字体预览 Unicode 范围的表示变得简单。但是请注意,更好的 Java 实现将对不在指定字体中的符号或字符使用字体替换,因此您需要确保您实际上获得了指定的字体。