Swing not displaying unicode characters
I've got some non-ascii characters I'm trying to display in a Swing JComboBox. The characters aren't displaying correctly, I get lots of weird characters where the non-ascii characters should be:
import javax.swing.*;
public class Test {
public static void main(String[] args) {
String[] choices = new String[]{"Good's","Bad’s","தமிழ்"};
for (String s : choices) System.out.println(s);
JComboBox choiceBox = new JComboBox(choices);
JFrame frame = new JFrame("Test");
frame.setSize(400, 400);
frame.add(choiceBox);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
(Note the slightly different apostrophe in Bad’s, which is what started this whole thing.)
The System.out.println
call displays the characters just fine in my terminal.
There are a bunch of questions on SO about this, and they suggest listing fonts from the GraphicsEnvironment and picking only ones that claim to display my characters. Unfortunately, this t开发者_如何学编程rick doesn't work for me.
Font font = new Font("Ariel", Font.PLAIN, 12);
for (String s : choices) assert font.canDisplayUpTo(s) < 0;
choiceBox.setFont(font);
The assert doesn't fail, but still displays garbled characters.
I'm on OSX 10.6.5, Java(TM) SE Runtime Environment (build 1.6.0_22-b04-307-10M3261)
Make sure your compiler uses the same encoding as your editor (your editor already uses the same as the console, it seems, and the compiler normally uses the default encoding of the VM, given by the file.encoding
property).
You can do this by giving the -encoding
option to the compiler, or the encoding=
attribute in ant.
The font you are trying to use doesn't have the required glyphs. canDisplay
methods fail for some reason on Mac. On linux and windows your code behaves as expected and assertion fails, but on Mac it doesn't fail. I had a similar problem with using some characters on Mac, I just went with Sans font cause it seemed like the most Unicode complete font. If you check out this thread you will find out its quite common problem. So maybe you want to go with what Costis suggested in comment and also checking out this.
Changes the font of JCombobox to Unicode supported font of Tamil. Download font from http://www.ildc.in/Tamil/GIST/htm/otfonts.htm
Font font = new Font("TamilFont", Font.PLAIN, 12);
for (String s : choices) assert font.canDisplayUpTo(s) < 0;
choiceBox.setFont(font);
精彩评论