This section provides a tutorial example on how to create a label with the javax.swing.JLabel class.
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, http://www.herongyang.com/
*/
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);
}
}
If you run this example, you will get:
Note: The pack() method causes the window to resize to fit the preferred size and layouts of its subcomponents.
Sample programs listed in this section have been tested with JDK 1.3.1, 1.4.1, 1.5.0, and 1.6.0.