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 trick 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With