Fra*_*oll 2 java unicode fonts swing jbutton
我在 Java 上使用 Swing 进行字符编码时遇到问题。我想写这个角色:
"\u2699"
Run Code Online (Sandbox Code Playgroud)
这是一个简单的 JButton 上的齿轮,但是当我启动我的程序时,我只得到一个带有正方形的 JButton 而不是齿轮。这是一行:
opt.setText("\u2699");
Run Code Online (Sandbox Code Playgroud)
其中 opt 是按钮。
按钮结果:
我可以更改 Swing 字符编码或其他内容吗?谢谢。
正如 Andreas 所提到的,使用Font支持该字符的 。但是除非为应用程序提供合适的字体,否则FontAPI 提供了在运行时发现兼容字体的方法。它提供了如下方法:
Font.canDisplay(char)Font.canDisplay(int)Font.canDisplayUpTo(String)在这个例子中,我们在这个系统上展示了十几种字体,这些字体将显示齿轮字符。
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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
360 次 |
| 最近记录: |