Unicode字符不兼容? [英] Unicode Character uncompatibility?
问题描述
我在Java上使用swing进行字符编码时遇到问题. 我要写这个字符:
I have a problem with character encoding using swing on Java. I want to write this character:
"\u2699"
这是一个简单JButton上的齿轮,但是当我启动程序时,我只会得到一个带有正方形的JButton,而没有齿轮.这是一行:
That is a gear on a simple JButton but when I start my program I get only a JButton with a square and not the gear. This is the line:
opt.setText("\u2699");
其中opt是按钮.
按钮结果:
我可以更改摇摆字符编码还是其他? 谢谢.
Can I change swing character encoding or something else? Thanks.
推荐答案
如Andreas所述,请使用支持该字符的Font
.但是,除非为应用程序提供合适的字体,否则Font
API会提供在运行时发现兼容字体的方法.它提供了以下方法:
As mentioned by Andreas, use a Font
that supports that character. But unless supplying a suitable font for the app., the Font
API provides ways of discovering compatible fonts at run-time. It provides methods like:
-
Font.canDisplay(char)
-
Font.canDisplay(int)
-
Font.canDisplayUpTo(String)
- 和其他..请参阅文档以获取所有这些信息的详细信息.
在此示例中,我们在该系统上显示了十二种字体,这些字体将显示齿轮字符.
In this example, we show the dozen fonts on this system that will display the gear character.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class GearFonts {
private JComponent ui = null;
int codepoint = 9881;
String gearSymbol = new String(Character.toChars(codepoint));
GearFonts() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new GridLayout(0,2,5,5));
ui.setBorder(new EmptyBorder(4,4,4,4));
Font[] fonts = GraphicsEnvironment.
getLocalGraphicsEnvironment().getAllFonts();
for (Font font : fonts) {
if (font.canDisplay(codepoint)) {
JButton button = new JButton(gearSymbol + " " + font.getName());
button.setFont(font.deriveFont(15f));
ui.add(button);
}
}
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
GearFonts o = new GearFonts();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
这篇关于Unicode字符不兼容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!