Creating Labels with javax.swing.JLabel Class

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) HerongYang.com. All Rights Reserved.
 */
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:

JLabel Test
JLabel Test

Note: The pack() method causes the window to resize to fit the preferred size and layouts of its subcomponents.



 

Table of Contents

 About This Book

 JDK (Java Development Kit)

 Introduction of Java Swing Package

 Graphics Environment of the Local System

 JFrame - Main Frame Class

JLabel - Swing Label Class

Creating Labels with javax.swing.JLabel Class

 Creating Labels with Chinese Characters

 JButton - Swing Button Class

 JCheckBox - Swing Check Box Class

 JRadioButton - Swing Radio Button Class

 JTextField - Swing Text Field Class

 JComboBox - Swing Combo Box Class

 Menu Bar, Menus, Menu Items and Listeners

 Creating Internal Frames inside the Main Frame

 Layout of Components in a Container

 LookAndFeel and UIManager

 Option Dialog Boxes

 JEditorPane - The Editor Pane Class

 SwingWorker - The Background Task Worker

 AWT (Abstract Windows Toolkit)

 Integration with Desktop System

 Outdated Tutorials

 References

 Full Version in PDF/EPUB