Search code examples
javainternationalizationjtextareanon-english

Internationalized string in JTextArea


How can I display any non-English characters in JTextArea? I tried different ways, but none works. The following code prints gibberish for any non-English character like Japanese. In debug mode, the variable msgUtf8Str indeed shows the local characters correctly. The supporting character set can be large and a sample includes: Japanese, Chinese (Mandarin), French, German etc.

String msgUtf8Str = null;
byte[] msgUtf8= message.getBytes(Charset.forName("UTF-8"));
try
{
    msgUtf8Str = new String(msgUtf8, "UTF-8");
}
catch(Exception ex){}       
txtMsg.append(msgUtf8Str + "\n");

Solution

  • Remove all of that code except the last line.

    You are using the UTF-8 charset to translate message into bytes, which you are then translating back into a String using the same charset. In other words, you have made a pointless round-trip conversion.

    The original String, message, is already suitable for displaying non-English characters. You do not need to use Charsets in any way.

    For instance:

    String message = "\u65e5\u672c\u8a9e \u4e2d\u6587 Fran\u00e7ais f\u00fcr";
    textMsg.append(message).append("\n");
    

    Here is a small demo:

    import java.awt.EventQueue;
    import javax.swing.JOptionPane;
    
    public class I18NDemo {
        public static void main(String[] args) {
            final String message =
                "\u65e5\u672c\u8a9e \u4e2d\u6587 Fran\u00e7ais f\u00fcr";
    
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    JOptionPane.showMessageDialog(null, message);
                    System.exit(0);
                }
            });
        }
    }