I'm trying to display this Unicode "\uD83D"
on a JButton
text, but when I compile it just shows the square of an unknown character.

- 168,117
- 40
- 217
- 433

- 41
- 1
- 3
-
1Change the font to one that can support the unicode characters – MadProgrammer Feb 19 '17 at 22:46
-
4A single [surrogate character](https://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates) like `'\uD83D'` is always illegal. Only a surrogate **pair** makes sense. – Thomas Fritsch Feb 19 '17 at 23:11
2 Answers
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
:
Font.canDisplayUpTo(String)
Font.canDisplayUpTo(CharacterIterator,start,limit)
Font.canDisplayUpTo(char[],start,limit)
E.G.
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

- 168,117
- 40
- 217
- 433
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 \uFFFF
.
A surrogate pair denotes the code point
1000016 + (H − D80016) × 40016 + (L − DC0016)
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 .

- 9,639
- 33
- 37
- 49