Java Unicode文本在awt标签中未正确显示
我有以下简单的Java测试程序:Java Unicode文本在awt标签中未正确显示,java,unicode,awt,Java,Unicode,Awt,我有以下简单的Java测试程序: import java.awt.*; public class test3 { public test3() { Frame f = new Frame(); f.setLayout(null); f.setBounds(50,50, 400,400); Label l = new Label("你好吗"); l.setBounds(10,100, 50,30);
import java.awt.*;
public class test3 {
public test3() {
Frame f = new Frame();
f.setLayout(null);
f.setBounds(50,50, 400,400);
Label l = new Label("你好吗");
l.setBounds(10,100, 50,30);
TextField t = new TextField("你好吗",20);
t.setBounds(100,100,50,30);
f.add(l);
f.add(t);
f.setVisible(true);
}
public static void main(String[] args) {
test3 t = new test3();
}
}
运行此测试程序的输出是3个方形框,用于显示标签文本,以及你好吗 (你的中文怎么样)在文本字段中
TextField
和Label
是awt组件,虽然在文本字段中显示unicode没有问题,但不确定如何让Label
正确显示unicode。awt标签使用的字体很可能有问题。您需要找到一种支持UTF-8的字体并使用它。但是,如果使用Swing组件而不是AWT组件,则可以正常工作:
import javax.swing.*;
public class Example {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setLayout(null);
f.setBounds(50,50, 400,400);
JLabel l = new JLabel("你好吗");
l.setBounds(10,100, 50,30);
JTextField t = new JTextField("你好吗",20);
t.setBounds(100,100,50,30);
f.add(l);
f.add(t);
f.setVisible(true);
}
}
输出:
标签
使用不支持UTF-8的默认字体。只需将标签的字体更改为支持UTF-8的字体即可
例如,您可以将TextField
的相同字体也设置为Label
的
l.setFont(t.getFont());
<>但是无论如何,你应该考虑使用<代码> Swing 而不是<代码> AWT组件。因为你是新来的,不要忘记接受最能帮助我你的意见的答案。另请参见为什么使用AWT?请参阅,了解放弃使用AWT组件而使用Swing的许多好理由。我尝试使用getFont().getName()打印逻辑字体名称,并且我为所有AWT组件(如Label、TextField、Button和Checkbox)获得了相同的默认字体设置。即使我加入了l.setFont(t.getFont())语句(尽管它们已经是相同的字体),unicode也不会显示在标签、按钮和复选框上。我想,TextArea将正确显示unicode,因为TextField和TextArea具有相同的父类。好的,我将改用Swing,因为AWT中的大多数组件都不支持unicode显示。谢谢你的帮助。