2

I have the following simple Java test program:

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();
    }
}

The output of running this test program is 3 square boxes for the label text, and 你好吗 (how are you as in Chinese) in the text field.

TextField and Label are awt components, while there is no problem displaying unicode in the text field, not sure how to get Label to display unicode correctly.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
  • Since you are new here don't forget to accept the answer which helped I your opinion most. See also http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Paul Wasilewski Jun 07 '16 at 17:20
  • Why use AWT? See [this answer](http://stackoverflow.com/questions/6255106/java-gui-listeners-without-awt/6255978#6255978) for many good reasons to abandon AWT using components in favor of Swing. – Andrew Thompson Jun 08 '16 at 05:17

2 Answers2

3

It is most likely an issue with the font that the awt Label uses. You will need to find a font that supports UTF-8 and use that. However, if you use Swing components instead of AWT components it works fine:

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);
    }
}

Output:

enter image description here

explv
  • 2,709
  • 10
  • 17
0

Label uses a default font which not supports UTF-8. Just change the font of Label to a font which supports UTF-8.

For example you can set the same font of TextField also for Label with

l.setFont(t.getFont());

But anyway you should consider to use swing instead of awt components.

Paul Wasilewski
  • 9,762
  • 5
  • 45
  • 49
  • I tried println the logical font name using getFont().getName(), and I have got the same default font setting for all AWT components like Label, TextField, Button, Checkbox. Even I put in l.setFont(t.getFont()) statement, (though they are already of the same font), unicode just wont display on Label, Button, and Checkbox. I guess, TextArea will display unicode correctly since TextField and TextArea have the same parent class. Ok, I will use Swing instead, since most components in AWT don't support unicode display. Thanks for the help. – raymondraymond1 Jun 08 '16 at 18:07