0

I cant use unicode characters in java. I put the tree unicode in and it just comes out as a small box and a 4. It's in an applet, and I put the code in public void paint(Graphics g) anyway the code is below

    g.drawString("\u1F334",150,150);

2 Answers2

2

From JLS 3.3:

A compiler for the Java programming language ("Java compiler") first recognizes Unicode escapes in its input, translating the ASCII characters \u followed by four hexadecimal digits to the UTF-16 code unit (§3.1) for the indicated hexadecimal value, and passing all other characters unchanged. Representing supplementary characters requires two consecutive Unicode escapes.

(emphasis added)

Specifically, you need the UTF-16 BE (big endian) encoding. For the palm tree, the sequence (as noted on the page you linked) is "\uD83C\uDF34".

yshavit
  • 42,327
  • 7
  • 87
  • 124
  • 1
    The fixed number of hex characters seems logical, in France for instance, we don't want to have "n\u00E9ant" printed as "nບnt", what we want is "néant" . – Arnaud Apr 27 '16 at 15:15
0

The Unicode code point U+1F334 represents a "character" outside the java char range. Java uses the UTF-16 Unicode encoding, using 16 bits for a char. And U+1F334 goes in the 3-byte range.

You can do:

int[] codepoints = { 0x1F334 };
String emoji = new String(codepoints, 0, codepoints.length);

This will yield a String with a pair of chars, though using the escaping format of UTF-16, and not something simple like \u1F33\u0004 (wrong).

However if the font cannot represent that Unicode char, you will receive a small box, now with the six digits 01F / 334.

Font font = ...
if (!font.canDisplay(0x1F334)) {
    s = s.replace(emoji, " :) ");
}

It is unlikely that every browser has a full Unicode font available. You could try usings Swing's HTML capability and use an embedded image in an HTML JTextPane or such.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • That did not work... It has to be in a java applet... – Dwane Brown Jr Apr 28 '16 at 14:41
  • A **JApplet** can do **swing**, an **Applet** only **awt**. Of course you may use `g.drawString` and maybe `g.drawImage` if you opt for an image i.o. text. – Joop Eggen Apr 28 '16 at 14:46
  • To be honest, as a normal user will not have a full Unicode font, it will be hard. Also applets might disappear from browsers, as the java browser plugin. For the font you might try to pass your own font in HTML/CSS, so you might refer it in the applet. Whether all that works... – Joop Eggen Apr 28 '16 at 14:50