Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display japanese characters in JTextArea

There is strange behaviour of JTextArea when displaying japanese characters - I get well-known blank rectangles instead of kanji. The mostly strange thing is that JTextField displays them perfectly (in both cases I use "Tahoma" font family). Also, if I put this code:

    Font f = new Font("123", Font.PLAIN, 12); // This font doesn't exists
    problemTextArea.setFont(f);

...before i write japanese string to the problemTextArea it displays kanji!

P.S. Sorry for my English.

Upd: I am using Windows

like image 486
Eskat0n Avatar asked Apr 05 '09 11:04

Eskat0n


1 Answers

The problem is that JTextArea uses a different default font than JTextField. I had the same problem in an application I wrote that had to support multi-languages.

The reason for your problem is that JTextArea is normally used to show a mono-spaced font, such as Courier New. Normally Java contains no additional mappings for a mono-spaced graphical font to display Kanji.

The fix you have works, because there is no font named "123", so the default is taken (dialog). The "dialog" font is internally mapped to a font family in the font.properties file of your platform. This will be the same font that JTextField uses.

I have the following fix, to ensure that the same font definition is used in ALL graphical components. You can also find the specific key for JTextArea and change it. This way you don't have to worry about the fonts of any component, they will be initialized with dialog.

Object fontDefinition = new UIDefaults.ProxyLazyValue("javax.swing.plaf.FontUIResource", null, new Object[] { "dialog", new Integer(Font.PLAIN), new Integer(12) });

java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
    Object key = keys.nextElement();
    Object value = UIManager.get(key);
    if (value instanceof javax.swing.plaf.FontUIResource) {
        UIManager.put(key, fontDefinition);
    }
}
like image 52
Mario Ortegón Avatar answered Oct 10 '22 05:10

Mario Ortegón