0

If a String contains certain unicode characters, they are displayed as boxes when in a JLabel, but are displayed correctly when in a JTextArea.

minimal_example_screenshot

Below is a minimal reproduction.

import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;

public class ShowText {
    static final String DEFAULT_TEXT = "1234567890"
        + "\u9dd7\u3400\u845b\u6e1a\u5653\ud840\udc0b\ud868\udd90\ud869\udeb2\u304b\u309a"
        + "---"
        + "\u9dd7\u3400\u845b\u6e1a\u5653\ud840\udc0b\ud868\udd90\ud869\udeb2\u304b\u309a"
        + "'12.txt";

    public static void main(String[] pArgs) throws Exception {

        JPanel jp = new JPanel(new BorderLayout());

        // Label text displayed incorrectly
        JLabel label = new JLabel(DEFAULT_TEXT);
        jp.add(label, BorderLayout.NORTH);

        jp.add(Box.createRigidArea(new Dimension(20,20)), BorderLayout.CENTER);

        // TextArea text displayed correctly
        JTextArea area = new JTextArea(DEFAULT_TEXT);
        JScrollPane scroll = new JScrollPane(area);
        jp.add(scroll, BorderLayout.SOUTH);

        JFrame jf = new JFrame();
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        jf.getContentPane().add(jp);
        jf.pack();
        jf.setSize(450, 100);
        jf.setVisible(true);
    }
}

Why are the characters not displayed correctly, and how can I make them display correctly?

(For reference, I'm running java 1.8.0_181 on macOS 10.14)

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
the_storyteller
  • 2,335
  • 1
  • 26
  • 37
  • 1
    Not all fonts support all unicode characters, you may need to change the font manually – MadProgrammer Oct 15 '18 at 22:19
  • Which fonts are used by default, and how can I change them? I assumed that the same font would be used for both Swing components. – the_storyteller Oct 15 '18 at 22:27
  • 1
    [Unicode Support in JTextArea Component](https://stackoverflow.com/questions/36630981/unicode-support-in-jtextarea-component) ... [Unicode characters in app doesn't show correctly](https://stackoverflow.com/questions/29028072/unicode-characters-in-app-doesnt-show-correctly) – MadProgrammer Oct 15 '18 at 22:33
  • Look to `Font.canDisplayUpTo(..)` to find fonts compatible with (that define glyphs to display them) particular Unicode chars. – Andrew Thompson Oct 15 '18 at 22:34

0 Answers0