Get foreign characters to appear in a JTextArea or other Swing component?

I’ve got some Swing components (a JTextArea and a JList) that have a bunch of strings in them. The strings are often foreign, as in I’ll have accented letters like é ï, etc.

Does anyone know a way I can get Swing to not do retarded character corruption like “Jouer √† √™tre Dieu” instead of “Jouer être Dieu.” If I write the data to a file there is no corruption, so I know it’s got something to do with Swing. I’ve tried changing the Font and that doesn’t seem to help.

Also, this isn’t as important, but it would be nice for ’ to be translated to ’ in the display. However, I don’t want to have to deal with putting in HTML to format it correctly, so putting it into a HTML parsing view is not a good solution.

I’ve never come across any problems with displaying UTF8 Strings in Swing components.
My guess is that the Strings are becoming corrupt before they are reaching Swing - likely because the Strings are being constructed from data incorrectly assumed to be 1 byte/character.

Where are the Strings coming from? what format are they being provided in? and how are you constructing the String objects?

The String objects are fine when I spit them out (later) to a text file.

I read them from a file with BufferedReader, store them in a String object, then put them into a StringBuffer, and JTextArea.setText(buffer.toString()). Then later a write them to a file, which has no formatting problems.

So what charset do you specify? (if any)

You need:
new BufferedReader(InputStreamReader(new FileInputStream(...), "UTF-8") )

Yeah, that did the trick. Thanks, Riven. Weird that it was able to output the text again just fine later with a PrintWriter.

That’s called: two bugs that cancel eachother out.

Assuming you don’t want to just do a replaceAll("’", “’”) in your text, you could accomplish this with a custom ListCellRenderer. Just a DefaultListCellRenderer subclass that does this, assuming your list items are Strings:


public Component getListCellRendererComponent(JList list,
                                              Object value,
                                              int index,
                                              boolean isSelected,
                                              boolean cellHasFocus) {
   value = ((String)value).replaceAll("'", "'");
   return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
}

:slight_smile:

Thanks BoBear, that’ll do the trick. I didn’t want to replace any part of the string because I need the string to stay as-is, I just want to display it differently.

You will also find that you have to use “heavyweight” mode in menus if your menus include full unicode.

JPopupMenu.setDefaultLightWeightPopupEnabled(false);

Keep in mind that String.replaceAll() uses regex… so don’t just pass in your exact-match-Strings.