Skip to Main Content
Java Swing, 2nd Edition
book

Java Swing, 2nd Edition

by Dave Wood, Robert Eckstein, Marc Loy, James Elliott, Brian Cole
November 2002
Intermediate to advanced content levelIntermediate to advanced
1278 pages
38h 26m
English
O'Reilly Media, Inc.
Content preview from Java Swing, 2nd Edition

Labels

Swing allows you to create labels that can contain text, images, or both. We’ll begin this chapter with a look at the JLabel class.

The JLabel class allows you to add basic, noninteractive labels to a user interface. Because of its inherent simplicity, there is no model class for JLabel. Figure 4-1 shows a class diagram for JLabel. We’ll get into the two relationships to Icon a little later.

JLabel class diagram

Figure 4-1. JLabel class diagram

JLabel objects may consist of both text and graphics (icons), but for simple text-only labels, the interface with JLabel is very similar to that of java.awt.Label. The code to create and display a very simple text label looks like this:

// SimpleJLabelExample.java
//
import javax.swing.*;

public class SimpleJLabelExample {
  public static void main(String[] args) {
    JLabel label = new JLabel("A Very Simple Text Label");

    JFrame frame = new JFrame( );
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane( ).add(label); // Adds to CENTER
    frame.pack( );
    frame.setVisible(true);
  }
}

Running this simple program produces the display shown in Figure 4-2.

A simple JLabel

Figure 4-2. A simple JLabel

Properties

The JLabel class contains the properties shown in Table 4-1. The icon and disabledIcon properties specify the icon to be displayed by default and when the label ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java Threads, 3rd Edition

Java Threads, 3rd Edition

Scott Oaks, Henry Wong

Publisher Resources

ISBN: 0596004087Errata PageSupplemental Content