是的,只要你有一個包含兩組字符的字體,你就可以在Java中顯示簡體和繁體中文文本。
我寫了這個簡短的程序來演示:使用
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
public class ChineseFonts {
public static final int GAP = 35;
public static final int FONTS_PER_LINE = 2;
public ChineseFonts(String s) {
Rectangle rect = new Rectangle(0, 0, 1024, 768);
BufferedImage bufferedImage = new BufferedImage((int) Math.ceil(rect.getWidth()), (int) Math.ceil(rect.getHeight()), BufferedImage.TYPE_4BYTE_ABGR);
Graphics graphics = bufferedImage.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(rect.x, rect.y, rect.width, rect.height);
graphics.setColor(Color.BLUE);
String title = "Chinese Fonts on " + System.getProperty("os.name") + ", version " + System.getProperty("os.version");
int fontY = 30;
printString(title, graphics, 0, fontY, new Font(Font.SERIF, Font.BOLD | Font.ITALIC, 28), false);
fontY += GAP + 10;
int counter = 0;
for (String fontName : new String[]{Font.MONOSPACED, Font.SANS_SERIF, Font.SERIF}) {
Font font = new Font(fontName, Font.PLAIN, 24);
printString(s, graphics, counter++, fontY, font, true);
if (counter % FONTS_PER_LINE == 0)
fontY += GAP;
}
Font[] localFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
List<Font> chineseFonts = new ArrayList<Font>();
String simplifiedAndTraditionalChinese = "????";
for (int j = 0; j < localFonts.length; j++) {
if (localFonts[j].canDisplayUpTo(simplifiedAndTraditionalChinese) == -1) {
chineseFonts.add(localFonts[j].deriveFont(24F));
}
}
for (Font font : chineseFonts) {
printString(s, graphics, counter++, fontY, font, true);
if (counter % FONTS_PER_LINE == 0)
fontY += GAP;
}
graphics.dispose();
try {
ImageIO.write(bufferedImage, "png", new File("chineseFonts.png"));
} catch (Exception e) {
// ignored
}
}
private void printString(String s, Graphics graphics, int counter, int y, Font font, boolean showFontDetails) {
graphics.setFont(font);
if (showFontDetails)
s = font.getFamily() + " " + s;
graphics.drawString(s, 20 + (counter % FONTS_PER_LINE) * 510, y);
if (showFontDetails)
System.out.println("Printing " + s + " using " + font.getName() + ", which is " + font.getFontName() + " in family " + font.getFamily());
}
public static void main(String args[]) {
new ChineseFonts("S: 漢字 T: 漢字");
}
}
的2個簡化和2個傳統的中國字是從維基百科頁面上的中國特色。當你運行它時,所有使用的字體都被打印到標準輸出,並且圖像以字體名稱和中文字符輸出。
這裏有3種邏輯字體和工作第一物理字體:
- 等寬
- SANSSERIF
- 襯線
- 宋體的Unicode斯小姐
任何使用情況下你需要在同一個組件上顯示傳統和簡體中文文本? – belgther 2012-02-07 08:14:27
我想讓用戶在不重新啓動應用程序的情況下即時切換語言。此外,列表中可用語言的名稱將以其原生腳本編寫,因此我希望這些語言也能正確顯示。 – ThVortex 2012-02-07 18:37:44
就你而言,我建議你設置字體和文字以呈現文字。首先你用一種字體渲染,然後用另一種字體渲染。它會起作用嗎? – belgther 2012-02-08 08:05:16