简体   繁体   中英

Display an Unicode character on JButton

我正在尝试在JButton文本上显示此Unicode "\?" ,但是在编译时,它仅显示未知字符的平方。

You need to set a font supporting the Unicode characters you want.
The following example relies on Code2000.ttf installed on my system.

public static void main(String[] args) throws Exception {
    SwingUtilities.invokeLater(() -> {
        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JButton button = new JButton("\u4E33");
        Font font = new Font("Code2000", Font.PLAIN, 36);
        button.setFont(font);
        frame.add(button);
        frame.pack();
        frame.setVisible(true);           
    });
}

中文按钮

When you use surrogate characters (in range D800–DFFF), you need to use a high and low surrogate pair. And be aware that this pair represents a Unicode point beyond \￿ .

A surrogate pair denotes the code point
10000 16 + (H − D800 16 ) × 400 16 + (L − DC00 16 )
where H and L are the numeric values of the high and low surrogates respectively.

An unpaired surrogate character in a string (as in the original question) is invalid, and will be rendered as 未知 .

Thomas gave a good answer, but note that in order to avoid guessing which installed fonts support a character or string, we can iterate the available fonts and check each using the canDisplayUpTo overloaded methods of Font :

EG

import java.awt.Font;
import java.awt.GraphicsEnvironment;

public class FontCheck {

    public static void main(String[] args) {
        String s = "\u4E33";
        Font[] fonts = GraphicsEnvironment.
                getLocalGraphicsEnvironment().getAllFonts();
        System.out.println("Total fonts: \t" + fonts.length);
        int count = 0;
        for (Font font : fonts) {
            if (font.canDisplayUpTo(s) < 0) {
                count++;
                System.out.println(font.getName());
            }
        }
        System.out.println("Compatible fonts: \t" + count);
    }
}

Output:

Total fonts:    391
Arial Unicode MS
Dialog.bold
Dialog.bolditalic
Dialog.italic
Dialog.plain
DialogInput.bold
DialogInput.bolditalic
DialogInput.italic
DialogInput.plain
Microsoft JhengHei
Microsoft JhengHei Bold
Microsoft JhengHei Light
Microsoft JhengHei UI
Microsoft JhengHei UI Bold
Microsoft JhengHei UI Light
Microsoft YaHei
Microsoft YaHei Bold
Microsoft YaHei Light
Microsoft YaHei UI
Microsoft YaHei UI Bold
Microsoft YaHei UI Light
Monospaced.bold
Monospaced.bolditalic
Monospaced.italic
Monospaced.plain
NSimSun
SansSerif.bold
SansSerif.bolditalic
SansSerif.italic
SansSerif.plain
Serif.bold
Serif.bolditalic
Serif.italic
Serif.plain
SimSun
Compatible fonts:   35

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM