如何在JTextArea中显示任何非英文字符?我尝试了不同的方法,但没有任何效果。以下代码显示任何非英语字符(如日语)的乱码。在调试模式下,变量msgUtf8Str确实正确显示了本地字符。辅助字符集可能很大,示例包括:日语,中文(普通话),法语,德语等。
String msgUtf8Str = null;
byte[] msgUtf8= message.getBytes(Charset.forName("UTF-8"));
try
{
msgUtf8Str = new String(msgUtf8, "UTF-8");
}
catch(Exception ex){}
txtMsg.append(msgUtf8Str + "\n");
最佳答案
删除所有代码,最后一行除外。
您正在使用UTF-8字符集将message
转换为字节,然后使用相同的字符集将其转换回字符串。换句话说,您进行了无意义的往返转换。
原始字符串message
已适合显示非英文字符。您无需以任何方式使用字符集。
例如:
String message = "\u65e5\u672c\u8a9e \u4e2d\u6587 Fran\u00e7ais f\u00fcr";
textMsg.append(message).append("\n");
这是一个小演示:
import java.awt.EventQueue;
import javax.swing.JOptionPane;
public class I18NDemo {
public static void main(String[] args) {
final String message =
"\u65e5\u672c\u8a9e \u4e2d\u6587 Fran\u00e7ais f\u00fcr";
EventQueue.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, message);
System.exit(0);
}
});
}
}