|
Swing JLabel
This chapter discusses the following problems:
- How to create labels
- How to create labels with Chinese characters
Creating Labels
Problem: I want to create a label with a text string.
Solution: This is easy, just instantiate an object of javax.swing.JLabel,
and add it to any container. Here is a sample program to show
you how to do this:
/**
* JLabelHello.java
* Copyright (c) 2002 by Dr. Herong Yang
*/
import java.awt.*;
import javax.swing.*;
public class JLabelHello {
public static void main(String[] a) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel l = new JLabel("Hello world!");
f.getContentPane().add(l);
f.pack();
f.setVisible(true);
}
}
Creating Labels with Chinese Characters
Problem: I want to create a label with Chinese characters.
Solution: Not very hard to do. See the following sample program:
/**
* JLabelChinese.java
* Copyright (c) 2002 by Dr. Herong Yang
*/
import java.awt.*;
import javax.swing.*;
public class JLabelChinese {
public static void main(String[] a) {
JLabel l = new JLabel();
l.setFont(new Font("SimSun",Font.PLAIN, 12));
l.setText("Hello world! - \u7535\u8111\u4F60\u597D\uFF01");
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(l);
f.pack();
f.setVisible(true);
}
}
To run this program, you need to have SimSun font installed on your system.
To verify this, search for \winnt\fonts\simsun.ttc if you are using Windows system.
|