This section provides a tutorial example on how to draw characters on frame using the drawString() method with a Chinese font selected.
Problem: I want to draw some Chinese characters in a frame.
Solution: You can do in the same way as described in the solution of the
previous question. In the paint() method, first change the font of the Graphics
object to a Unicode font that supports Chinese characters. Then use drawString()
utility method to draw the string with Chinese characters.
The following sample code, JFramePaintChinese.java, shows you how to do this.
/**
* JFramePaintChinese.java
* Copyright (c) 2002 by Dr. Herong Yang, http://www.herongyang.com/
*/
import java.awt.*;
import javax.swing.*;
public class JFramePaintChinese {
public static void main(String[] a) {
JFrame f = new JFrame();
f.setTitle("Drawing Graphics in Frames");
f.setBounds(100,50,500,300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(new MyComponent());
f.setVisible(true);
}
static class MyComponent extends JComponent {
public void paint(Graphics g) {
g.setFont(new Font("SimSun",Font.PLAIN, 12));
g.drawString("Hello world! - \u7535\u8111\u4F60\u597D\uFF01",
100,50);
}
}
}
If you run this example, you will get:
Note 1: You don't need JDK 1.4.2 to draw Chinese characters in a component.
JDK 1.3.1 is enough to run this sample code.
Note 2: You need to have SimSun installed on your system. To verify this,
search for \winnt\fonts\simsun.ttc if you are using Windows system.
Sample programs listed in this section have been tested with JDK 1.3.1, 1.4.2, 1.5.0. and 1.6.0