Unicode 文本在 awt 标签中显示不正确
Unicode text is not displayed correctly in awt Label
我有以下简单的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);
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);
}
}
输出:
Label
使用不支持 UTF-8 的默认字体。只需将 Label
的字体更改为支持 UTF-8 的字体即可。
例如,您可以为 Label
和
设置与 TextField
相同的字体
l.setFont(t.getFont());
但无论如何你应该考虑使用 swing
而不是 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);
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);
}
}
输出:
Label
使用不支持 UTF-8 的默认字体。只需将 Label
的字体更改为支持 UTF-8 的字体即可。
例如,您可以为 Label
和
TextField
相同的字体
l.setFont(t.getFont());
但无论如何你应该考虑使用 swing
而不是 awt
组件。