Friday, March 4, 2011

Setting unicode characters in java frames

How to display unicode characters (e.g. japanese) in the title of a JFrame in java swing in a Windows XP m/c without the Japanese language pack? It looks like setting the title text to Japanese unicode characters and the font to MS Mincho is not enough. While this is all you need to do to display unicode characters in Swing labels?

From stackoverflow
  • "without the Japanese language pack" ?

    It seems you have to at least download the language font...

    alt text

    The font is the only thing that needs to be installed on your client machine to run the application.

    Using the font is lots easier in Swing unlike in AWT.
    For AWT components i.e one that has a native peer, you need to customize the settings of the JRE i.e modify font.properties under /jre/lib to include the font you have installed under each font type.

    In your Swing application, you just need to set the font of the Swing component before setting its text.

    The link at the beginning of the post contains a complete example.
    Small extract:

    JFrame frame = new JFrame();
    String string = "\u30b7\u30f3\u30d7\u30eb\u30c6\u30ad\u30b9\u30c8\u30a8\u30c7\u30a3\u30bf";
    JLabel label = new JLabel();
    label.setFont(new Font("MS Mincho",Font.PLAIN, 12));
    label.setText(string);
    frame.getContentPane().add(label);
    frame.setFont(new Font("MS Mincho",Font.PLAIN, 12));
    frame.setTitle(string);
    


    The general documentation for java J2SE6 (1.6.0) is here, included the Font Configuration Files

    From Java5 and later, you do not need font.properties file anymore, since you can load a font file in order to create/use a font.

    String fontFileName = "yourfont.ttf";
    InputStream is = this.getClass().getResourceAsStream(fontFileName);
    Font ttfBase = Font.createFont(Font.TRUETYPE_FONT, is);
    Font ttfReal = ttfBase.deriveFont(Font.PLAIN, 24);
    
  • Thanks!. I saw that post. Things are working fine with Swing components. It is the JFrame title that is giving trouble. I am using windows XP SP2, so MS Mincho is already available in the windows fonts folder. As for changing the JRE settings, I am using JDK 1.6.0_03 and I did not find any font.properties file in the /jre/lib folder.

    VonC : That means you may need to create the appropriate font.properties file. I just completed my answer with 1.6.0 links describing those files.
    VonC : Actually, with Java5+, you do not need font.properties anymore. See my extended answer

0 comments:

Post a Comment