---
title: "swing英文版xp乱码问题解决"
author: "skull"
date: "2010-12-15T16:37:00Z"
tags: []
categories: ["编程语言"]
slug: "swing-xp"
draft: false
lastmod: "2010-12-15T16:37:00Z"
id: 843059
url: "https://skull.iteye.com/blog/843059"
---

最近在维护swing程序时，有客户发现英文版xp下存在乱码问题（由于某些原因用户不能换系统），一开始以为是操作

 

系统设置问题，但用户说其他软件中文显示都正常，于是

 

找了VMware装了英文版的windows xp  一试 果然是乱码。

 

分析原因如下:其他软件中文显示都正常 说明os中文字库已装，估计是和jre有关，于是

 

就找和jre有关编码集问题

 

有人说和编译时候的encoding参数有关

 

样例代码在中文平台上编译，生成zhclass  
样例代码在英文平台上编译，输出enclass  
(1) zhclass在中文平台上执行ok,但是在英文平台上不行  
(2) enclass在英文平台上执行ok,但是在中文平台上不行  
出处：[http://oznyang.iteye.com/blog/30697](http://oznyang.iteye.com/blog/30697)

 

我一直没找到这个参数怎么会使用，但是找到了执行时设置支付编码集的命令

 

-D&lt;name&gt;=&lt;value&gt; set a system property

 

如： javaw -Dfile.encoding=GBK -cp  xx.jar com.xx.main

 

System.getProperties() 中和字符集有关的变量有：

file.encoding  
sun.io.unicode.encoding  
sun.jnu.encoding  
user.country  
user.languag

 

进尝试发现file.encoding有对控制台的System.out.println有用加了后无乱码，但是界面上乱码依旧。

 

必须当作启动参数设置，在程序中System.setProperties("file.encoding", "GBK")无效果

后来继续网上搜索，找到原因如下：

swing中UIManager根据操作系统语言设置的不同会使用了默认的字体

 

英文版windows xp下默认字体为：  
family=Tahoma,name=Tahoma,style=plain,size=11

Tahoma好像不支持中文乱码全是方框需替换成本地指定的能显示中文的字体样式 比如: 宋体

```
Font font = new Font("宋体", Font.PLAIN, 12);
Enumeration<Object> keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
    Object key = keys.nextElement();
    if (UIManager.get(key) instanceof FontUIResource){
        UIManager.put(key, new FontUIResource(font));
    }
    else if(UIManager.get(key) instanceof Font){
     UIManager.put(key, font);
    }
    //System.out.println("key:"+key+"  value:"+UIManager.get(key));
}

```

 启动时强制指定UIManager中的字体设置即可解决界面上的方框乱码，

 

这时发现 标题栏还是乱码。。。

又继续搜索，发现标题栏是使用皮肤包substance的标题栏

```
JFrame.setDefaultLookAndFeelDecorated(true);
```

   
找了半天也没找到解决方法，目前只能使用swing自带的标题栏，不加上面语句就可以正常显示。

 

附件为测试demo