Chapter 4. Labels and Icons
We’ll begin our look at the Swing components with the
JLabel class. In addition, we’ll look at
Swing’s new Icon interface and an
implementation of this interface called ImageIcon.
With just these few new constructs, you’ll begin to see how
much Swing has done to improve UI development in Java.
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
The JLabel
class allows you to add basic,
nonfunctional labels to a user interface. Because of their inherent
simplicity, there is no model class for JLabel
components. Figure 4.1 shows a class diagram for
JLabel. We’ll get into the two relations to
Icon a little later.

Figure 4-1. JLabel class diagram
Unlike java.awt.Label objects,
JLabel objects may consist of both text and
graphics (icons). For simple text labels, the interface to
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.addWindowListener(new BasicWindowMonitor());
frame.getContentPane().add(label);
frame.pack();
frame.setVisible(true);
}
}Running this simple program ...
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.
Read now
Unlock full access